views:

71

answers:

4

I understood what brace expansion is.
But I don't know where I use that.

When do you use it?
Please give me some convenient examples.

Thanks.

+2  A: 

For example, make a backup of all your files in a directory:

for i in * ; do
    cp "$i"{,.bak}
done
Benoit
That can't possibly work.
Marcelo Cantos
Sorry, moved {,.bak} outside of the quoted part. was a typo.
Benoit
Ok, that makes more sense. In fact, I didn't realise until now that the path components don't need to exist.
Marcelo Cantos
A: 

You use it whenever you want to match against multiple choices. E.g.,

ls src/{Debug,Release}/*.o  # List all .o files in the Debug and Release directories.
Marcelo Cantos
+3  A: 

The range expression form of brace expansion is used in place of seq in a for loop:

for i in {1..100}
do
    something    # 100 times
done
Dennis Williamson
+1  A: 

In bash, you use brace expansion if you want to create a range, eg

for r in {0..100}

for r in {0..10..2} #with step of 2

for z in {a..z}

Instead of using external commands such as seq 0 100. Also , brace expansion can be used to list file types, eg

for file in *.{txt,jpg}.

This list all files that has txt and jpg extensions.

ghostdog74