Brace expansion is used to generate arbitrary strings. The specified strings are used to generate **all possible combinations** with the optional surrounding prefixes and suffixes.
Usually it's used to generate mass-arguments for a command, that follow a specific naming-scheme.
:!: It is the very first step in expansion-handling, it's important to understand that. When you use
Another common pitfall is to assume that a range like ''{1..200}'' can be expressed with variables using ''{$a..$b}''. Due to what I described above, it **simply is not possible**, because it's the very first step in doing expansions. A possible way to achieve this, if you really can't handle this in another way, is using the ''eval'' command, which basically evaluates a commandline twice: <code>eval echo {$a..$b}</code> For instance, when embedded inside a for loop : <code>for i in $(eval echo {$a..$b})</code> This requires that the entire command be properly escaped to avoid unexpected expansions. If the sequence expansion is to be assigned to an array, another method is possible using [[commands:builtin:declare|declaration commands]]: <code>declare -a 'pics=(img{'"$a..$b"'}.png)'; mv "${pics[@]}" ../imgs</code> This is significantly safer, but one must still be careful to control the values of $a and $b. Both the exact quoting, and explicitly including "-a" are important.
The brace expansion is present in two basic forms, **string lists** and **ranges**.
It can be switched on and off under runtime by using the ''set'' builtin and the option ''-B'' and ''+B'' or the long option ''braceexpand''. If brace expansion is enabled, the stringlist in ''SHELLOPTS'' contains ''braceexpand''.
The brace expansion is only performed, if the given string list is really a **list of strings**, i.e., if there is a minimum of one "'',''" (comma)! Something like ''{money}'' doesn't expand to something special, it's really only the text "''{money}''".
Brace expansion using ranges is written giving the startpoint and the endpoint of the range. This is a "sequence expression". The sequences can be of two types
* integers (optionally zero padded, optionally with a given increment)
When you combine more brace expansions, you effectively use a brace expansion as prefix or suffix for another one. Let's generate all possible combinations of uppercase letters and digits:
The most optimal possible brace expansion to expand n arguments of course consists of n's prime factors. We can use the "factor" program bundled with GNU coreutils to emit a brace expansion that will expand any number of arguments.
"Braceify" generates the expansion code itself. In this example we inject that output into a template which displays the most terse brace expansion code that would expand ''"$arg"'' 1,000,000 times if evaluated. In this case, the output is: