6

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.

Benjamin
  • 10,085
  • 19
  • 80
  • 130

4 Answers4

4

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
  • 346,391
  • 90
  • 374
  • 439
2

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

for i in * ; do
    cp "$i"{,.bak}
done
Benoit
  • 76,634
  • 23
  • 210
  • 236
2

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
  • 327,991
  • 56
  • 259
  • 343
0

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
  • 181,030
  • 38
  • 327
  • 365