EXPANSION Expansion is performed on the command line after it has been split into words. There are seven kinds of expansion performed: brace expansion, tilde expansion, parameter and variable expansion, command substitu‐ tion, arithmetic expansion, word splitting, and pathname expansion. The order of expansions is: brace expansion; tilde expansion, parameter and variable expansion, arithmetic expansion, and command substitution (done in a left-to-right fashion); word splitting; and pathname expan‐ sion. On systems that can support it, there is an additional expansion avail‐ able: process substitution. This is performed at the same time as tilde, parameter, variable, and arithmetic expansion and command sub‐ stitution. After these expansions are performed, quote characters present in the original word are removed unless they have been quoted themselves (quote removal). Only brace expansion, word splitting, and pathname expansion can in‐ crease the number of words of the expansion; other expansions expand a single word to a single word. The only exceptions to this are the ex‐ pansions of "$@" and "${name[@]}", and, in most cases, $* and ${name[*]} as explained above (see PARAMETERS). Brace Expansion Brace expansion is a mechanism by which arbitrary strings may be gener‐ ated. This mechanism is similar to pathname expansion, but the file‐ names generated need not exist. Patterns to be brace expanded take the form of an optional preamble, followed by either a series of comma-sep‐ arated strings or a sequence expression between a pair of braces, fol‐ lowed by an optional postscript. The preamble is prefixed to each string contained within the braces, and the postscript is then appended to each resulting string, expanding left to right. Brace expansions may be nested. The results of each expanded string are not sorted; left to right order is preserved. For example, a{d,c,b}e expands into `ade ace abe'. A sequence expression takes the form {x..y[..incr]}, where x and y are either integers or single letters, and incr, an optional increment, is an integer. When integers are supplied, the expression expands to each number between x and y, inclusive. Supplied integers may be prefixed with 0 to force each term to have the same width. When either x or y begins with a zero, the shell attempts to force all generated terms to contain the same number of digits, zero-padding where necessary. When letters are supplied, the expression expands to each character lexico‐ graphically between x and y, inclusive, using the default C locale. Note that both x and y must be of the same type (integer or letter). When the increment is supplied, it is used as the difference between each term. The default increment is 1 or -1 as appropriate. Brace expansion is performed before any other expansions, and any char‐ acters special to other expansions are preserved in the result. It is strictly textual. Bash does not apply any syntactic interpretation to the context of the expansion or the text between the braces. A correctly-formed brace expansion must contain unquoted opening and closing braces, and at least one unquoted comma or a valid sequence ex‐ pression. Any incorrectly formed brace expansion is left unchanged. A { or , may be quoted with a backslash to prevent its being considered part of a brace expression. To avoid conflicts with parameter expan‐ sion, the string ${ is not considered eligible for brace expansion, and inhibits brace expansion until the closing }. This construct is typically used as shorthand when the common prefix of the strings to be generated is longer than in the above example: mkdir /usr/local/src/bash/{old,new,dist,bugs} or chown root /usr/{ucb/{ex,edit},lib/{ex?.?*,how_ex}} Brace expansion introduces a slight incompatibility with historical versions of sh. sh does not treat opening or closing braces specially when they appear as part of a word, and preserves them in the output. Bash removes braces from words as a consequence of brace expansion. For example, a word entered to sh as file{1,2} appears identically in the output. The same word is output as file1 file2 after expansion by bash. If strict compatibility with sh is desired, start bash with the +B option or disable brace expansion with the +B option to the set com‐ mand (see SHELL BUILTIN COMMANDS below). Tilde Expansion If a word begins with an unquoted tilde character (`~'), all of the characters preceding the first unquoted slash (or all characters, if there is no unquoted slash) are considered a tilde-prefix. If none of the characters in the tilde-prefix are quoted, the characters in the tilde-prefix following the tilde are treated as a possible login name. If this login name is the null string, the tilde is replaced with the value of the shell parameter HOME. If HOME is unset, the home direc‐ tory of the user executing the shell is substituted instead. Other‐ wise, the tilde-prefix is replaced with the home directory associated with the specified login name. If the tilde-prefix is a `~+', the value of the shell variable PWD re‐ places the tilde-prefix. If the tilde-prefix is a `~-', the value of the shell variable OLDPWD, if it is set, is substituted. If the char‐ acters following the tilde in the tilde-prefix consist of a number N, optionally prefixed by a `+' or a `-', the tilde-prefix is replaced with the corresponding element from the directory stack, as it would be displayed by the dirs builtin invoked with the tilde-prefix as an argu‐ ment. If the characters following the tilde in the tilde-prefix con‐ sist of a number without a leading `+' or `-', `+' is assumed. If the login name is invalid, or the tilde expansion fails, the word is unchanged. Each variable assignment is checked for unquoted tilde-prefixes immedi‐ ately following a : or the first =. In these cases, tilde expansion is also performed. Consequently, one may use filenames with tildes in as‐ signments to PATH, MAILPATH, and CDPATH, and the shell assigns the ex‐ panded value. Bash also performs tilde expansion on words satisfying the conditions of variable assignments (as described above under PARAMETERS) when they appear as arguments to simple commands. Bash does not do this, except for the declaration commands listed above, when in posix mode. Parameter Expansion The `$' character introduces parameter expansion, command substitution, or arithmetic expansion. The parameter name or symbol to be expanded may be enclosed in braces, which are optional but serve to protect the variable to be expanded from characters immediately following it which could be interpreted as part of the name. When braces are used, the matching ending brace is the first `}' not escaped by a backslash or within a quoted string, and not within an em‐ bedded arithmetic expansion, command substitution, or parameter expan‐ sion. ${parameter} The value of parameter is substituted. The braces are required when parameter is a positional parameter with more than one digit, or when parameter is followed by a character which is not to be interpreted as part of its name. The parameter is a shell parameter as described above PARAMETERS) or an array reference (Arrays). If the first character of parameter is an exclamation point (!), and parameter is not a nameref, it introduces a level of indirection. Bash uses the value formed by expanding the rest of parameter as the new pa‐ rameter; this is then expanded and that value is used in the rest of the expansion, rather than the expansion of the original parameter. This is known as indirect expansion. The value is subject to tilde ex‐ pansion, parameter expansion, command substitution, and arithmetic ex‐ pansion. If parameter is a nameref, this expands to the name of the parameter referenced by parameter instead of performing the complete indirect expansion. The exceptions to this are the expansions of ${!prefix*} and ${!name[@]} described below. The exclamation point must immediately follow the left brace in order to introduce indirec‐ tion. In each of the cases below, word is subject to tilde expansion, parame‐ ter expansion, command substitution, and arithmetic expansion. When not performing substring expansion, using the forms documented be‐ low (e.g., :-), bash tests for a parameter that is unset or null. Omitting the colon results in a test only for a parameter that is un‐ set. ${parameter:-word} Use Default Values. If parameter is unset or null, the expan‐ sion of word is substituted. Otherwise, the value of parameter is substituted. ${parameter:=word} Assign Default Values. If parameter is unset or null, the ex‐ pansion of word is assigned to parameter. The value of parame‐ ter is then substituted. Positional parameters and special pa‐ rameters may not be assigned to in this way. ${parameter:?word} Display Error if Null or Unset. If parameter is null or unset, the expansion of word (or a message to that effect if word is not present) is written to the standard error and the shell, if it is not interactive, exits. Otherwise, the value of parameter is substituted. ${parameter:+word} Use Alternate Value. If parameter is null or unset, nothing is substituted, otherwise the expansion of word is substituted. ${parameter:offset} ${parameter:offset:length} Substring Expansion. Expands to up to length characters of the value of parameter starting at the character specified by off‐ set. If parameter is @ or *, an indexed array subscripted by @ or *, or an associative array name, the results differ as de‐ scribed below. If length is omitted, expands to the substring of the value of parameter starting at the character specified by offset and extending to the end of the value. length and offset are arithmetic expressions (see ARITHMETIC EVALUATION below). If offset evaluates to a number less than zero, the value is used as an offset in characters from the end of the value of pa‐ rameter. If length evaluates to a number less than zero, it is interpreted as an offset in characters from the end of the value of parameter rather than a number of characters, and the expan‐ sion is the characters between offset and that result. Note that a negative offset must be separated from the colon by at least one space to avoid being confused with the :- expansion. If parameter is @ or *, the result is length positional parame‐ ters beginning at offset. A negative offset is taken relative to one greater than the greatest positional parameter, so an offset of -1 evaluates to the last positional parameter. It is an expansion error if length evaluates to a number less than zero. If parameter is an indexed array name subscripted by @ or *, the result is the length members of the array beginning with ${pa‐ rameter[offset]}. A negative offset is taken relative to one greater than the maximum index of the specified array. It is an expansion error if length evaluates to a number less than zero. Substring expansion applied to an associative array produces un‐ defined results. Substring indexing is zero-based unless the positional parame‐ ters are used, in which case the indexing starts at 1 by de‐ fault. If offset is 0, and the positional parameters are used, $0 is prefixed to the list. ${!prefix*} ${!prefix@} Names matching prefix. Expands to the names of variables whose names begin with prefix, separated by the first character of the IFS special variable. When @ is used and the expansion appears within double quotes, each variable name expands to a separate word. ${!name[@]} ${!name[*]} List of array keys. If name is an array variable, expands to the list of array indices (keys) assigned in name. If name is not an array, expands to 0 if name is set and null otherwise. When @ is used and the expansion appears within double quotes, each key expands to a separate word. ${#parameter} Parameter length. The length in characters of the value of pa‐ rameter is substituted. If parameter is * or @, the value sub‐ stituted is the number of positional parameters. If parameter is an array name subscripted by * or @, the value substituted is the number of elements in the array. If parameter is an indexed array name subscripted by a negative number, that number is in‐ terpreted as relative to one greater than the maximum index of parameter, so negative indices count back from the end of the array, and an index of -1 references the last element. ${parameter#word} ${parameter##word} Remove matching prefix pattern. The word is expanded to produce a pattern just as in pathname expansion, and matched against the expanded value of parameter using the rules described under Pat‐ tern Matching below. If the pattern matches the beginning of the value of parameter, then the result of the expansion is the expanded value of parameter with the shortest matching pattern (the ``#'' case) or the longest matching pattern (the ``##'' case) deleted. If parameter is @ or *, the pattern removal op‐ eration is applied to each positional parameter in turn, and the expansion is the resultant list. If parameter is an array vari‐ able subscripted with @ or *, the pattern removal operation is applied to each member of the array in turn, and the expansion is the resultant list. ${parameter%word} ${parameter%%word} Remove matching suffix pattern. The word is expanded to produce a pattern just as in pathname expansion, and matched against the expanded value of parameter using the rules described under Pat‐ tern Matching below. If the pattern matches a trailing portion of the expanded value of parameter, then the result of the ex‐ pansion is the expanded value of parameter with the shortest matching pattern (the ``%'' case) or the longest matching pat‐ tern (the ``%%'' case) deleted. If parameter is @ or *, the pattern removal operation is applied to each positional parame‐ ter in turn, and the expansion is the resultant list. If param‐ eter is an array variable subscripted with @ or *, the pattern removal operation is applied to each member of the array in turn, and the expansion is the resultant list. ${parameter/pattern/string} ${parameter//pattern/string} ${parameter/#pattern/string} ${parameter/%pattern/string} Pattern substitution. The pattern is expanded to produce a pat‐ tern just as in pathname expansion. Parameter is expanded and the longest match of pattern against its value is replaced with string. string undergoes tilde expansion, parameter and vari‐ able expansion, arithmetic expansion, command and process sub‐ stitution, and quote removal. The match is performed using the rules described under Pattern Matching below. In the first form above, only the first match is replaced. If there are two slashes separating parameter and pattern (the second form above), all matches of pattern are replaced with string. If pattern is preceded by # (the third form above), it must match at the beginning of the expanded value of parameter. If pattern is preceded by % (the fourth form above), it must match at the end of the expanded value of parameter. If the expansion of string is null, matches of pattern are deleted. If string is null, matches of pattern are deleted and the / following pattern may be omitted. If the patsub_replacement shell option is enabled using shopt, any unquoted instances of & in string are replaced with the matching portion of pattern. Quoting any part of string inhibits replacement in the expansion of the quoted portion, including replacement strings stored in shell variables. Backslash will escape & in string; the back‐ slash is removed in order to permit a literal & in the replace‐ ment string. Backslash can also be used to escape a backslash; \\ results in a literal backslash in the replacement. Users should take care if string is double-quoted to avoid unwanted interactions between the backslash and double-quoting, since backslash has special meaning within double quotes. Pattern substitution performs the check for unquoted & after expanding string; shell programmers should quote any occurrences of & they want to be taken literally in the replacement and ensure any in‐ stances of & they want to be replaced are unquoted. If the nocasematch shell option is enabled, the match is per‐ formed without regard to the case of alphabetic characters. If parameter is @ or *, the substitution operation is applied to each positional parameter in turn, and the expansion is the re‐ sultant list. If parameter is an array variable subscripted with @ or *, the substitution operation is applied to each mem‐ ber of the array in turn, and the expansion is the resultant list. ${parameter^pattern} ${parameter^^pattern} ${parameter,pattern} ${parameter,,pattern} Case modification. This expansion modifies the case of alpha‐ betic characters in parameter. The pattern is expanded to pro‐ duce a pattern just as in pathname expansion. Each character in the expanded value of parameter is tested against pattern, and, if it matches the pattern, its case is converted. The pattern should not attempt to match more than one character. The ^ op‐ erator converts lowercase letters matching pattern to uppercase; the , operator converts matching uppercase letters to lowercase. The ^^ and ,, expansions convert each matched character in the expanded value; the ^ and , expansions match and convert only the first character in the expanded value. If pattern is omit‐ ted, it is treated like a ?, which matches every character. If parameter is @ or *, the case modification operation is applied to each positional parameter in turn, and the expansion is the resultant list. If parameter is an array variable subscripted with @ or *, the case modification operation is applied to each member of the array in turn, and the expansion is the resultant list. ${parameter@operator} Parameter transformation. The expansion is either a transforma‐ tion of the value of parameter or information about parameter itself, depending on the value of operator. Each operator is a single letter: U The expansion is a string that is the value of parameter with lowercase alphabetic characters converted to upper‐ case. u The expansion is a string that is the value of parameter with the first character converted to uppercase, if it is alphabetic. L The expansion is a string that is the value of parameter with uppercase alphabetic characters converted to lower‐ case. Q The expansion is a string that is the value of parameter quoted in a format that can be reused as input. E The expansion is a string that is the value of parameter with backslash escape sequences expanded as with the $'...' quoting mechanism. P The expansion is a string that is the result of expanding the value of parameter as if it were a prompt string (see PROMPTING below). A The expansion is a string in the form of an assignment statement or declare command that, if evaluated, will recreate parameter with its attributes and value. K Produces a possibly-quoted version of the value of param‐ eter, except that it prints the values of indexed and as‐ sociative arrays as a sequence of quoted key-value pairs (see Arrays above). a The expansion is a string consisting of flag values rep‐ resenting parameter's attributes. k Like the K transformation, but expands the keys and val‐ ues of indexed and associative arrays to separate words after word splitting. If parameter is @ or *, the operation is applied to each posi‐ tional parameter in turn, and the expansion is the resultant list. If parameter is an array variable subscripted with @ or *, the operation is applied to each member of the array in turn, and the expansion is the resultant list. The result of the expansion is subject to word splitting and pathname expansion as described below. Command Substitution Command substitution allows the output of a command to replace the com‐ mand name. There are two forms: $(command) or `command` Bash performs the expansion by executing command in a subshell environ‐ ment and replacing the command substitution with the standard output of the command, with any trailing newlines deleted. Embedded newlines are not deleted, but they may be removed during word splitting. The com‐ mand substitution $(cat file) can be replaced by the equivalent but faster $(< file). When the old-style backquote form of substitution is used, backslash retains its literal meaning except when followed by $, `, or \. The first backquote not preceded by a backslash terminates the command sub‐ stitution. When using the $(command) form, all characters between the parentheses make up the command; none are treated specially. Command substitutions may be nested. To nest when using the backquoted form, escape the inner backquotes with backslashes. If the substitution appears within double quotes, word splitting and pathname expansion are not performed on the results. Arithmetic Expansion Arithmetic expansion allows the evaluation of an arithmetic expression and the substitution of the result. The format for arithmetic expan‐ sion is: $((expression)) The old format $[expression] is deprecated and will be removed in up‐ coming versions of bash. The expression undergoes the same expansions as if it were within dou‐ ble quotes, but double quote characters in expression are not treated specially and are removed. All tokens in the expression undergo param‐ eter and variable expansion, command substitution, and quote removal. The result is treated as the arithmetic expression to be evaluated. Arithmetic expansions may be nested. The evaluation is performed according to the rules listed below under ARITHMETIC EVALUATION. If expression is invalid, bash prints a message indicating failure and no substitution occurs. Process Substitution Process substitution allows a process's input or output to be referred to using a filename. It takes the form of <(list) or >(list). The process list is run asynchronously, and its input or output appears as a filename. This filename is passed as an argument to the current com‐ mand as the result of the expansion. If the >(list) form is used, writing to the file will provide input for list. If the <(list) form is used, the file passed as an argument should be read to obtain the output of list. Process substitution is supported on systems that sup‐ port named pipes (FIFOs) or the /dev/fd method of naming open files. When available, process substitution is performed simultaneously with parameter and variable expansion, command substitution, and arithmetic expansion. Word Splitting The shell scans the results of parameter expansion, command substitu‐ tion, and arithmetic expansion that did not occur within double quotes for word splitting. The shell treats each character of IFS as a delimiter, and splits the results of the other expansions into words using these characters as field terminators. If IFS is unset, or its value is exactly , the default, then sequences of , , and at the beginning and end of the results of the previous expansions are ignored, and any sequence of IFS characters not at the beginning or end serves to delimit words. If IFS has a value other than the default, then sequences of the whitespace characters space, tab, and newline are ignored at the beginning and end of the word, as long as the whitespace character is in the value of IFS (an IFS white‐ space character). Any character in IFS that is not IFS whitespace, along with any adjacent IFS whitespace characters, delimits a field. A sequence of IFS whitespace characters is also treated as a delimiter. If the value of IFS is null, no word splitting occurs. Explicit null arguments ("" or '') are retained and passed to commands as empty strings. Unquoted implicit null arguments, resulting from the expansion of parameters that have no values, are removed. If a parame‐ ter with no value is expanded within double quotes, a null argument re‐ sults and is retained and passed to a command as an empty string. When a quoted null argument appears as part of a word whose expansion is non-null, the null argument is removed. That is, the word -d'' becomes -d after word splitting and null argument removal. Note that if no expansion occurs, no splitting is performed. Pathname Expansion After word splitting, unless the -f option has been set, bash scans each word for the characters *, ?, and [. If one of these characters appears, and is not quoted, then the word is regarded as a pattern, and replaced with an alphabetically sorted list of filenames matching the pattern (see Pattern Matching below). If no matching filenames are found, and the shell option nullglob is not enabled, the word is left unchanged. If the nullglob option is set, and no matches are found, the word is removed. If the failglob shell option is set, and no matches are found, an error message is printed and the command is not executed. If the shell option nocaseglob is enabled, the match is per‐ formed without regard to the case of alphabetic characters. Note that when using range expressions like [a-z] (see below), letters of the other case may be included, depending on the setting of LC_COLLATE. When a pattern is used for pathname expansion, the character ``.'' at the start of a name or immediately following a slash must be matched explicitly, unless the shell option dotglob is set. In order to match the filenames ``.'' and ``..'', the pattern must begin with ``.'' (for example, ``.?''), even if dotglob is set. If the globskipdots shell option is enabled, the filenames ``.'' and ``..'' are never matched, even if the pattern begins with a ``.''. When not matching pathnames, the ``.'' character is not treated specially. When matching a path‐ name, the slash character must always be matched explicitly by a slash in the pattern, but in other matching contexts it can be matched by a special pattern character as described below under Pattern Matching. See the description of shopt below under SHELL BUILTIN COMMANDS for a description of the nocaseglob, nullglob, globskipdots, failglob, and dotglob shell options. The GLOBIGNORE shell variable may be used to restrict the set of file names matching a pattern. If GLOBIGNORE is set, each matching file name that also matches one of the patterns in GLOBIGNORE is removed from the list of matches. If the nocaseglob option is set, the match‐ ing against the patterns in GLOBIGNORE is performed without regard to case. The filenames ``.'' and ``..'' are always ignored when GLOBIG‐ NORE is set and not null. However, setting GLOBIGNORE to a non-null value has the effect of enabling the dotglob shell option, so all other filenames beginning with a ``.'' will match. To get the old behavior of ignoring filenames beginning with a ``.'', make ``.*'' one of the patterns in GLOBIGNORE. The dotglob option is disabled when GLOBIGNORE is unset. The pattern matching honors the setting of the extglob shell option. Pattern Matching Any character that appears in a pattern, other than the special pattern characters described below, matches itself. The NUL character may not occur in a pattern. A backslash escapes the following character; the escaping backslash is discarded when matching. The special pattern characters must be quoted if they are to be matched literally. The special pattern characters have the following meanings: * Matches any string, including the null string. When the globstar shell option is enabled, and * is used in a pathname expansion context, two adjacent *s used as a single pattern will match all files and zero or more di‐ rectories and subdirectories. If followed by a /, two adjacent *s will match only directories and subdirecto‐ ries. ? Matches any single character. [...] Matches any one of the enclosed characters. A pair of characters separated by a hyphen denotes a range expres‐ sion; any character that falls between those two charac‐ ters, inclusive, using the current locale's collating se‐ quence and character set, is matched. If the first char‐ acter following the [ is a ! or a ^ then any character not enclosed is matched. The sorting order of characters in range expressions, and the characters included in the range, are determined by the current locale and the val‐ ues of the LC_COLLATE or LC_ALL shell variables, if set. To obtain the traditional interpretation of range expres‐ sions, where [a-d] is equivalent to [abcd], set value of the LC_ALL shell variable to C, or enable the globasci‐ iranges shell option. A - may be matched by including it as the first or last character in the set. A ] may be matched by including it as the first character in the set. Within [ and ], character classes can be specified using the syntax [:class:], where class is one of the following classes defined in the POSIX standard: alnum alpha ascii blank cntrl digit graph lower print punct space upper word xdigit A character class matches any character belonging to that class. The word character class matches letters, digits, and the character _. Within [ and ], an equivalence class can be specified us‐ ing the syntax [=c=], which matches all characters with the same collation weight (as defined by the current lo‐ cale) as the character c. Within [ and ], the syntax [.symbol.] matches the collat‐ ing symbol symbol. If the extglob shell option is enabled using the shopt builtin, the shell recognizes several extended pattern matching operators. In the following description, a pattern-list is a list of one or more patterns separated by a |. Composite patterns may be formed using one or more of the following sub-patterns: ?(pattern-list) Matches zero or one occurrence of the given patterns *(pattern-list) Matches zero or more occurrences of the given patterns +(pattern-list) Matches one or more occurrences of the given patterns @(pattern-list) Matches one of the given patterns !(pattern-list) Matches anything except one of the given patterns Theextglob option changes the behavior of the parser, since the paren‐ theses are normally treated as operators with syntactic meaning. To ensure that extended matching patterns are parsed correctly, make sure that extglob is enabled before parsing constructs containing the pat‐ terns, including shell functions and command substitutions. When matching filenames, the dotglob shell option determines the set of filenames that are tested: when dotglob is enabled, the set of file‐ names includes all files beginning with ``.'', but ``.'' and ``..'' must be matched by a pattern or sub-pattern that begins with a dot; when it is disabled, the set does not include any filenames beginning with ``.'' unless the pattern or sub-pattern begins with a ``.''. As above, ``.'' only has a special meaning when matching filenames. Complicated extended pattern matching against long strings is slow, es‐ pecially when the patterns contain alternations and the strings contain multiple matches. Using separate matches against shorter strings, or using arrays of strings instead of a single long string, may be faster. Quote Removal After the preceding expansions, all unquoted occurrences of the charac‐ ters \, ', and " that did not result from one of the above expansions are removed.