When do you use brace expansion?

Brace expansion is very useful if you have long path names. I use it as a quick way to backup a file:

cp /a/really/long/path/to/some/file.txt{,.bak}

will copy /a/really/long/path/to/some/file.txt to /a/really/long/path/to/some/file.txt.bak

You can also use it in a sequence. I once did so to download lots of pages from the web:

wget http://domain.com/book/page{1..5}.html

or

for i in {1..100}
do
   #do something 100 times
done

Brace expansion comes very handy when creating large directory structures:

mkdir -p dir1/{subdir1,subdir2}/{subsubdir1,subsubdir2}

This will give you

find dir1 -type d
dir1
dir1/subdir1
dir1/subdir1/subsubdir1
dir1/subdir1/subsubdir2
dir1/subdir2
dir1/subdir2/subsubdir1
dir1/subdir2/subsubdir2

You could even go one step further and put brace expansion into brace expansion:

mkdir -p dir1/{subdir{1,2}}/{subsubdir{1,2}}

This will give you the same directory structure as the example above.


I use it when I want to reduce typing:

geany /path/to/file1 /path/to/file2
# versus
geany /path/to/file{1,2}

Another example:

wajig install libpam0g-dev libiw-dev libdb-dev
# versus
wajig install lib{pam0g,iw,db}-dev