Bash - Brace Expansion {}

> Procedural Languages > Bash Shell and (Unix|Linux) Utilities (XCU)

1 - About

Brace expansion is a mechanism by which arbitrary strings may be generated.

This mechanism is similar to pathname expansion, but the filenames generated need not exist.

Advertising

3 - Syntax

Patterns to be brace expanded take the form of an optional preamble, followed by either:

  • a series of comma-separated strings
  • or a sequence expression between a pair of braces,

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

3.1 - Series of comma-separated strings

echo 'Hello '{Rixt,Madelief,Melissa}$' !\n'
Hello Rixt !
Hello Madelief !
Hello Melissa !

3.1.1 - Usage / Example

This construct is typically used as shorthand when the common prefix of the strings to be generated is longer than in the above example:

Example:

  • with mkdir
mkdir /usr/local/src/bash/{old,new,dist,bugs}

Resulting in

mkdir /usr/local/src/bash/old /usr/local/src/bash/new /usr/local/src/bash/dist /usr/local/src/bash/bugs
chown root /usr/{ucb/{ex,edit},lib/{ex?.?*,how_ex}}

Resulting in:

chown root /usr/ucb/ex /usr/ucb/edit /usr/lib/ex?.?* /usr/lib/how_ex
Advertising

3.2 - Sequence Expression

4 - Management

4.1 - Order

Brace expansion is performed before any other expansions, and any characters 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.

4.2 - Nested

Brace expansions may be nested. The results of each expanded string are not sorted; left to right order is preserved. For example,

echo a{d,c,b}e

expands into:

ade ace abe

4.3 - Sh

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:

  • in sh identically in the output.
  • in bash: as file1 file2 after expansion.

If strict compatibility with sh is desired:

  • start bash with the +B option
  • or disable brace expansion with the +B option to the set command.
Advertising
lang/bash/brace_expansion.txt · Last modified: 2018/09/16 12:42 by gerardnico