Bash Brace Expansion

Bash brace expansion is used to generate stings at the command line or in a shell script. The syntax for brace expansion consists of either a sequence specification or a comma separated list of items inside curly braces "{}". A sequence consists of a starting and ending item separated by two periods "..".

Some examples and what they expand to:

  {aa,bb,cc,dd}  => aa bb cc dd
  {0..12}        => 0 1 2 3 4 5 6 7 8 9 10 11 12
  {3..-2}        => 3 2 1 0 -1 -2
  {a..g}         => a b c d e f g
  {g..a}         => g f e d c b a
If the brace expansion has a prefix or suffix string then those strings are included in the expansion:
  a{0..3}b       => a0b a1b a2b a3b
Brace expansions can be nested:
  {a,b{1..3},c}  => a b1 b2 b3 c

Counted loops in bash can be implemented a number of ways without brace expansion:

# Three expression for loop:
for (( i = 0; i < 20; i++ ))
do
    echo $i
done
# While loop:
i=0
while [[ $i -lt 20 ]]
do
    echo $i
    let i++
done
# For loop using seq:
for i in $(seq 0 19)
do
    echo $i
done
A counted for loop using bash sequences requires the least amount of typing:
for i in {0..19}
do
    echo $i
done
But beyond counted for loops, brace expansion is the only way to create a loop with non-numeric "indexes":
for i in {a..z}
do
    echo $i
done

Brace expansion can also be useful when passing multiple long pathnames to a command. Instead of typing:

  # rm /a/long/path/foo /a/long/path/bar
You can simply type:
  # rm /a/long/path/{foo,bar}

Brace expansion is enabled via the "set -B" command and the "-B" command line option to the shell and disabled via "set +B" and "+B" on the command line.

Mitch Frazier is an embedded systems programmer at Emerson Electric Co. Mitch has been a contributor to and a friend of Linux Journal since the early 2000s.

Load Disqus comments