Brace Expansion

Su Suriya Ravichandran Updated 06 Dec 2026
8 min read ·Lesson 50 of 205

Brace expansion generates several words from one short pattern. Writing file.{txt,md,log} makes Bash produce file.txt file.md file.log before the command even starts. It is a text-generation feature: it builds names and sequences without looking at the file system, which makes it ideal for creating folders, copies and numbered lists with very little typing.

Understanding the Concept

When Bash finds a pair of braces that contains a comma-separated list or a range, it replaces the word with one new word for each item. Any text directly before the opening brace (the preamble) and after the closing brace (the postscript) is attached to every generated word.

echo {a,b,c}
echo file.{txt,md,log}
echo pre{1,2}post

Output:

a b c
file.txt file.md file.log
pre1post pre2post
  • {a,b,c} became three words.
  • In file.{txt,md,log}, the preamble file. was added to the front of each item.
  • In pre{1,2}post, both the preamble pre and the postscript post were attached.

Brace expansion happens early, before variable expansion, command substitution and wildcard expansion. By the time the command runs, it receives only the finished words. The command never sees the braces.

Syntax

There are two forms.

A list uses commas between items:

{item1,item2,item3}

A sequence uses two dots between a start and an end, and optionally a step:

{start..end}
{start..end..step}

Both forms need at least one comma or .. inside the braces and no unquoted spaces. If those conditions are not met, Bash leaves the text unchanged.

Sequences of Numbers and Letters

A range of numbers counts up or down automatically, depending on which end is larger:

echo {1..5}
echo {5..1}
echo {-3..3}
echo {3..-3}

Output:

1 2 3 4 5
5 4 3 2 1
-3 -2 -1 0 1 2 3
3 2 1 0 -1 -2 -3

Letters work the same way, in the order of the character set:

echo {a..e}
echo {E..A}

Output:

a b c d e
E D C B A

A single-element range produces just that value:

echo {5..5}

Output:

5

Steps

A third number sets how far to move each time:

echo {0..20..5}
echo {10..0..5}
echo {a..k..3}
echo {a..z..5}

Output:

0 5 10 15 20
10 5 0
a d g j
a f k p u z

The direction comes from the start and end values, so {10..0..5} counts down even though the step is written as positive. Writing {10..0..-5} produces the same list. Letters can also use a step, which skips letters in the alphabet.

Zero Padding

If either end of a numeric range has a leading zero, every number is padded to the same width:

echo {01..05}
echo {008..012}

Output:

01 02 03 04 05
008 009 010 011 012

The second range shows that the width is taken from the longest end, so 8 became 008. Zero padding keeps file names in the right order when they are sorted alphabetically.

Combining Braces

When a word contains more than one pair of braces, Bash produces every combination. The leftmost pair changes slowest.

echo {a,b}{1,2}
echo {A..C}{1..2}
echo {x,y,z}-{1,2}

Output:

a1 a2 b1 b2
A1 A2 B1 B2 C1 C2
x-1 x-2 y-1 y-2 z-1 z-2

Each item of the first brace is paired with each item of the second. In the last example, three items times two items gives six words.

Braces can also be nested. The inner pair is expanded as one of the outer items:

echo {a,b{1,2},c}

Output:

a b1 b2 c

The middle item b{1,2} expanded to b1 b2, so the outer list ended up with four words.

Padded ranges combine in the same way:

echo {1..3}{01..02}

Output:

101 102 201 202 301 302

Empty Items

An empty item in a list produces the preamble and postscript by themselves. This is the trick behind shortcuts for copying and renaming:

echo a{,b}
echo file{,.bak}

Output:

a ab
file file.bak

a{,b} has two items, an empty one and b, so it produced a and ab. The pattern file{,.bak} produced file and file.bak, which is exactly the pair of names a backup command needs.

Practical Applications

Creating Directory Structures

One command can create a whole project layout. mkdir -p creates missing parent folders as needed, and brace expansion supplies the names:

mkdir -p project/{src,docs,tests}
ls project

Output:

docs
src
tests

Two braces in one path create a full set of combinations:

mkdir -p site/{css,js,img}/{min,src}
find site -type d | sort

Output:

site
site/css
site/css/min
site/css/src
site/img
site/img/min
site/img/src
site/js
site/js/min
site/js/src

mkdir received six paths, one for each pair, and created every directory it needed along the way.

Making a Backup Copy

The empty-item trick gives a short way to copy a file next to the original:

touch config.yaml
cp config.yaml{,.bak}
ls config.yaml*

Output:

config.yaml
config.yaml.bak

Bash expanded config.yaml{,.bak} to config.yaml config.yaml.bak, so the command that ran was cp config.yaml config.yaml.bak.

Renaming an Extension

Listing the old and new extensions in one brace saves typing the base name twice:

touch report.txt
mv report.{txt,md}
ls report.*

Output:

report.md

The expansion report.{txt,md} became report.txt report.md, which is the source and destination for mv.

Creating Many Files at Once

mkdir -p logs && cd logs
touch app-{2026-01,2026-02,2026-03}.log
ls

Output:

app-2026-01.log
app-2026-02.log
app-2026-03.log

Looping Over a Range

A brace sequence supplies the list for a for loop:

for f in {1..3}; do echo "round $f"; done

Output:

round 1
round 2
round 3

Building Paths in One Command

printf '%s\n' dir{1..3}/file.txt
echo /usr/{bin,sbin}/env | tr ' ' '\n'

Output:

dir1/file.txt
dir2/file.txt
dir3/file.txt
/usr/bin/env
/usr/sbin/env

printf repeats its format for each argument, so each generated path was printed on its own line. The tr command in the second example converted the spaces between the words into newlines.

Brace Expansion Is Not Globbing

A wildcard such as *.txt is expanded only to files that exist. Brace expansion generates words whether or not anything with that name exists:

echo {nonexistent1,nonexistent2}
echo nonexist*

Output:

nonexistent1 nonexistent2
nonexist*

The braces produced two words even though no such files exist. The wildcard matched nothing, so Bash left the pattern as it was. Because brace expansion runs first, you can combine them: ls *.{jpg,png} first becomes ls *.jpg *.png, and then each wildcard is matched against the real files.

When Braces Are Not Expanded

Bash leaves the text alone if the brace does not describe a list or a valid range:

echo {a}
echo {}
echo a{b}c
echo {1..}
echo {a..5}

Output:

{a}
{}
a{b}c
{1..}
{a..5}

A single item with no comma, an empty pair, an open-ended range and a range that mixes a letter with a number are all printed literally. These rules are useful because common text such as ${var} and JSON-like braces is not disturbed.

Quoting or escaping the braces also prevents expansion:

echo "{a,b,c}"
echo '{a,b,c}'
echo \{a,b,c\}
echo {"a b",c}

Output:

{a,b,c}
{a,b,c}
{a,b,c}
a b c

The first three commands printed the braces as text. In the last one, the braces were unquoted, so they expanded, and the quotes around "a b" kept that item as a single word with a space in it. You can confirm the word boundaries with printf:

printf '[%s]\n' {"a b",c}

Output:

[a b]
[c]

Braces and Variables

Because brace expansion happens before variables are expanded, a sequence cannot use a variable as its start or end:

n=3
echo {1..$n}
eval echo {1..$n}

Output:

{1..3}
1 2 3

At the time Bash looked at {1..$n}, the endpoint was the text $n, which is not a number, so the pattern was not a valid range. The result then showed the braces with the variable already expanded. Using eval makes Bash read the line twice, which works but carries risks that a later lesson on security explains. A safer choice for a variable count is a C-style loop or seq:

for ((i=1; i<=n; i++)); do printf '%s ' $i; done; echo
for i in $(seq 1 $n); do printf '%s ' $i; done; echo

Output:

1 2 3 
1 2 3 

A list, in contrast, may contain variables, because each item is expanded afterward:

a=A; b=B
echo {$a,$b}
v="x,y"
echo {$v}

Output:

A B
{x,y}

{$a,$b} already has a comma in the pattern, so Bash expanded it into two words and then replaced each variable. In {$v}, the comma comes from inside the variable, which is not visible at brace-expansion time, so no list was formed and the braces stayed.

Availability

Brace expansion is a Bash feature, and it is not part of the basic POSIX shell standard. A shell such as Dash, which is often what /bin/sh points to on Debian and Ubuntu, does not support it:

sh -c 'echo {a,b,c}'

Output (on a system where sh is Dash):

{a,b,c}

A script that starts with #!/bin/sh should therefore avoid braces like these, while a script with a Bash shebang can rely on them.

Brace expansion can be turned off and on in Bash with the B option of set:

set +B
echo {a,b}
set -B
echo {a,b}

Output:

{a,b}
a b

set +B disabled the feature, so the braces were printed as typed. set -B turned it back on. The option is on by default.

0 Comments

Reviewed before they appear

No comments yet.

Bash
Introduction to Bash What Is a Shell? What Is Bash (Bourne Again Shell)? Bash vs. Shell vs. Terminal Bash vs. sh, Zsh, and Fish Where Bash Is Used: Linux, DevOps, and Automation Installing Bash on Linux Using Bash on macOS Using Bash on Windows with WSL Checking Your Bash Version Opening and Using a Terminal Running Your First Bash Command Understanding Command Syntax and Arguments Bash Built-in Commands vs. External Commands Working with pwd, ls, and cd Creating Files and Directories with touch and mkdir Copying, Moving, and Renaming Files Removing Files and Directories Safely Viewing Files with cat, less, head, and tail Searching for Files with find Searching Text with grep Understanding File Paths and Wildcards Using man Pages and Command Help Bash Script Structure Creating Your First Bash Script Understanding the Shebang (#!/usr/bin/env bash) Making a Script Executable with chmod Running a Bash Script in Different Ways Writing Comments in Bash Using echo and printf Reading User Input with read Displaying Helpful Messages in Scripts Using Semicolons and Newlines Bash Variables: Declaration and Usage Rules for Naming Bash Variables Environment Variables Local Variables vs. Environment Variables Exporting Variables with export Common Environment Variables: HOME, PATH, USER, and PWD Read-Only Variables with readonly Removing Variables with unset Command-Line Arguments: $0, $1, and More Special Parameters: $#, $?, $$, $!, $@, and $* Positional Parameters and shift Default Values with Parameter Expansion Single Quotes vs. Double Quotes Escaping Special Characters Command Substitution with $(...) Arithmetic Expansion with $((...)) Brace Expansion Tilde Expansion and Home Directories Filename Expansion and Globbing Understanding Word Splitting Parameter Expansion Basics Why Quoting Variables Matters Standard Input, Standard Output, and Standard Error Redirecting Output with > and >> Redirecting Input with < Redirecting Errors with 2> Combining Standard Output and Standard Error Using Pipes (|) to Connect Commands Using tee to Save and Display Output Here Documents with << Here Strings with <<< Command Lists with ;, &&, and || Conditional Statements with if, then, and fi Using elif and else Testing Conditions with test and [ ] Using [[ ]] for Bash Conditionals Comparing Strings in Bash Checking Whether Files Exist Checking File Types and Permissions Integer Comparisons in Bash Logical Operators: &&, ||, and ! Using case Statements Pattern Matching in case Common Conditional Statement Mistakes for Loops in Bash C-Style for Loops while Loops until Loops Looping Through Files and Directories Looping Through Command Output Safely break and continue Nested Loops select Loops for Simple Menus Avoiding Infinite Loops Defining and Calling Bash Functions Passing Arguments to Functions Returning Status Codes from Functions Understanding return vs. echo in Functions Local Variables in Functions Function Scope and Variable Visibility Organizing Scripts into Functions Sourcing Other Bash Files with source Reusable Bash Utility Functions Indexed Arrays in Bash Creating and Accessing Array Elements Adding and Removing Array Elements Looping Through Arrays Array Length and Indices Associative Arrays in Bash Iterating Over Associative Arrays Passing Arrays to Functions Common Array Pitfalls Processing Text with grep, sed, and awk Using cut, sort, uniq, and wc Finding and Replacing Text with sed Extracting Columns with awk Parsing CSV-Like Text from the Command Line Working with Filenames That Contain Spaces Safe File Handling with find -print0 and xargs -0 Temporary Files with mktemp Reading Files Line by Line Appending Logs to a File Understanding Exit Codes Checking Command Success with $? Using exit to End a Script Fail-Fast Scripts with set -e: Benefits and Caveats Using set -u and set -o pipefail Combining Strict Mode Options Safely Handling Errors with if Statements Traps with trap Cleaning Up Temporary Files on Exit Writing Useful Error Messages Debugging Scripts with bash -x Parsing Script Arguments Validating Required Arguments Handling Optional Arguments Parsing Options with getopts Building Help Messages with --help Setting Defaults for Optional Parameters Handling Unknown Options and Invalid Input Creating Interactive Menus in Bash Foreground and Background Processes Running Commands in the Background with & Managing Jobs with jobs, fg, and bg Waiting for Processes with wait Capturing Process IDs with $! and $$ Sending Signals with kill Handling Interrupts and Termination Signals Running Commands with timeout Basic Process Monitoring from Bash Aliases and Shell Functions: When to Use Each Customizing the Bash Prompt (PS1) Bash Startup Files: .bashrc, .bash_profile, and Profile Interactive vs. Non-Interactive Bash Shell Options with set shopt: Enabling Bash-Specific Options Directory Stack with pushd, popd, and dirs Process Substitution with <(...) and >(...) Advanced Parameter Expansion Pattern Matching and Extended Globbing Bash Script Security Fundamentals Avoiding Command Injection in Shell Scripts Quoting User Input Safely Why eval Is Risky and Safer Alternatives Handling Secrets and Credentials in Scripts Using Least Privilege in Automation Scripts Safe Use of rm and Destructive Commands Validating Paths and User-Supplied Filenames ShellCheck: Static Analysis for Bash Scripts Writing Readable and Maintainable Bash Automating Backups with Bash Creating Log Rotation and Cleanup Scripts Checking Disk Usage and Free Space Monitoring CPU, Memory, and System Load Checking Website Availability with curl Automating Updates on Ubuntu and Debian Scheduling Bash Scripts with cron Using Lock Files to Prevent Duplicate Runs Building a Simple Health-Check Script Sending Notifications from Bash Scripts Using Bash in Git Workflows Bash Scripts for Docker Automation Automating Docker Container Health Checks Using Bash in CI/CD Pipelines Environment Configuration for Deployment Scripts Automating SSH Tasks with Bash Deploying a Web Application with a Bash Script Using Bash to Process Application Logs Building Repeatable Development Setup Scripts Bash Debugging Techniques Using set -x and PS4 for Debug Traces Testing Bash Scripts with Bats Mocking Commands During Script Tests Testing Error Paths and Exit Codes Writing Portable Shell Scripts Bash-Specific Syntax vs. POSIX Shell Syntax Using ShellCheck in a Development Workflow Performance Tips for Bash Scripts Build an Interactive Calculator Build a File and Directory Organizer Build a Timestamped Backup Script Build a Log File Analyzer Build a Bulk File Renaming Tool Build a System Resource Monitoring Script Build a Website Uptime Checker Build a User Account Audit Report Build a Database Backup Automation Script Build a Docker Cleanup Helper Build a Server Health-Check and Alert Script Build a Deployment Automation Script Build a Menu-Driven Linux Administration Toolkit Build a Safe Automated Backup and Restore Workflow
Ask about this post
AI Ask about this post

Ask questions about Brace Expansion and get answers drawn from it.

Signed-in readers only.