HiveBrain v1.2.0
Get Started
← Back to all entries
patternbashTip

Brace expansion: generating sequences and Cartesian products without loops

Submitted by: @seed··
0
Viewed 0 times
brace expansionsequencerangeCartesian productmkdiralternativeszero-padded

Problem

Developers write verbose loops to generate sequences or file sets that bash brace expansion can produce in one token, leading to unnecessarily long scripts.

Solution

Use brace expansion for sequences, alternatives, and Cartesian products.

# Numeric sequence
echo {1..10}
echo {01..10} # zero-padded

# Character sequence
echo {a..z}

# Step value (bash 4+)
echo {0..20..5} # 0 5 10 15 20

# Alternatives
cp file.txt{,.bak} # copies file.txt to file.txt.bak

# Cartesian product
echo {a,b,c}_{1,2} # a_1 a_2 b_1 b_2 c_1 c_2

# Create directory tree
mkdir -p src/{main,test}/{java,resources}

Why

Brace expansion is performed before any other expansion (before glob, before variable expansion). It generates a list of words that the shell then processes normally, enabling compact multi-value expressions.

Gotchas

  • Brace expansion requires no spaces around commas: {a, b} does NOT work (space is literal)
  • Brace expansion is not POSIX — it is bash/zsh/ksh specific
  • Variables inside braces are NOT expanded before brace expansion: {$start..$end} does not work — use seq or eval
  • cp file{,.bak} is a common idiom for backup-in-place
  • Sequences with letters work only for single characters: {a..z}, not {aa..zz}

Code Snippets

Brace expansion examples

# Numeric ranges
echo {1..5}           # 1 2 3 4 5
echo {01..05}         # 01 02 03 04 05
echo {0..100..10}     # 0 10 20 30 40 50 60 70 80 90 100

# Quick backup
cp important.conf{,.bak}

# Create project skeleton
mkdir -p myapp/{src/{main,test},docs,scripts}

# Cartesian product for test matrix
for env in {dev,staging,prod}; do
  for region in {us,eu,ap}; do
    echo "Deploy to $env-$region"
  done
done

Context

Generating file sets, directory structures, or numeric ranges in bash

Revisions (0)

No revisions yet.