Sign up ×


When do you use it?

share|improve this question

6 Answers 6

up vote 35 down vote accepted







for i in {1..100}
   #do something 100 times
share|improve this answer
This is a shame. I just discovered it but do the backup thing on extra-long paths for years without knowing rhis. Thanks. –  smonff May 20 '14 at 12:41
@Patrick: That fails because program gets three words: "-f file1" "-f file2" "-f file3", instead of 6: "-f" "file1" "-f" "file2" "-f" "file3". –  musiphil May 18 at 18:52
@dogbane: Using expansion for use in a for loop is a bit pointless, since you can write for ((i=1; i<=100; i++)) and it is more efficient. –  musiphil May 18 at 18:54

Brace expansion comes very handy when creating large directory structures:


This will give you

find dir1 -type d




share|improve this answer

I use it when I want to reduce typing:

# 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
share|improve this answer


$ diff tests.{out,output}/041
share|improve this answer

Some frequent cases for me are:

For renaming:

mv myText.{txt,tex}


mv myText.tex{,.old}


cp myText.tex{,.backup}


For comparing (already mentioned):

diff path{1,2}/a.txt
share|improve this answer

There are several great answers here, but none of them mention when not to use brace expansion. Like the other answerers, I use brace expansion on the command line quite a bit. I also use it in my aliases and functions since I can expect a smart shell.

I do not use it in my shell scripts (unless there's some other reason the scripts should be bash or zsh, though in those cases, it's best to upgrade to a "real" scripting language like perl or python). Brace expansion is not portable since it is not in the POSIX shell standard. Even if it works in your /bin/sh-shebanged shell scripts, it will not work on systems with more stripped /bin/sh shells (e.g. dash).

In the case of a difference of a single digit, you don't need brace expansion; a character class will suffice:


diff file{1,2}


diff file[12]
share|improve this answer
A difference is that file{1,2} will always expand to file1 file2, while file[12] expands only to existing filenames: i.e. if file1 exists but file2 doesn't, file[12] expands to file1 only. The [] expansion is really a restricted version of ? expansion (and they are called "pathname expansions"). –  musiphil May 18 at 18:57
Correct, brace expansion is not shell globbing (a.k.a. pathname expansion). That's a good call-out that hasn't really been mentioned yet: brace expansion is better at noting unexpectedly absent paths. You can also glob inside brace expansion. –  Adam Katz May 18 at 21:28

Your Answer


