# Bash Brace Expansion

`{}` generates file lists, number sequences and combinations before the command ever runs — `mkdir -p project/{src,bin,docs}`, `cp config.yml{,.backup}`, `touch log-{001..030}.txt`. one of those things where once you learn it you start seeing uses for it everywhere.

## how {a,b,c} expands before the command runs

bash expands `{}` before doing anything else. so:

```bash
echo {one,two,three}
# one two three
```

doesn't look impressive until you realize it works with any command.

## mkdir -p {src,bin,docs} and the cp file{,.backup} trick

make a project structure in one shot:

```bash
mkdir -p project/{src,bin,docs,tests}
```

quick backup of a file (this one is *chef's kiss*):

```bash
cp config.yml{,.backup}
# expands to: cp config.yml config.yml.backup
```

the empty string before the comma is doing the heavy lifting there. took me a sec to get that the first time.

rename extension:

```bash
mv report.{txt,md}
```

nuke multiple file types:

```bash
rm *.{log,tmp,bak}
```

## number and letter ranges: {1..10}, {a..z}, {01..20}

```bash
echo {1..10}        # 1 2 3 4 5 6 7 8 9 10
echo {a..z}          # the whole alphabet
echo {01..20}        # zero-padded: 01 02 03 ... 20
echo {0..100..5}     # steps of 5 (bash 4+ only)
```

great for batch creating files:

```bash
touch log-{001..030}.txt
```

## nesting braces: {web,api}-{dev,staging,prod}

```bash
echo {web,api}-{dev,staging,prod}
# web-dev web-staging web-prod api-dev api-staging api-prod
```

combinatorial explosion in a good way.

## braces expand even when the files don't exist

braces expand whether or not files exist. globs (`*`) only match real files. so `{a,b,c}` always gives you three items. `*.txt` matches nothing if there's no .txt files, and bash hands the literal `*.txt` to the command. different tools for different jobs.

---

see also: [Bash Variable Tricks](/articles/bash-variable-tricks), [Bash Quick Loops](/articles/bash-quick-loops), [Bash History Expansion](/articles/bash-history-expansion)

[the bash man page on expansion](https://man7.org/linux/man-pages/man1/bash.1.html#EXPANSION)
