BASH: Using brace expansion

There's a nice feature of BASH which is to use a comma delimited list of strings inside of curly braces to reduce the amount of typing:

here's an example of using brace expansion to create log files for apache:

sudo touch {access,error}.log

Something seen less often is a blank entry like so:

cp foo{,.bck}

Which is shorthand for cp foo foo.bck. This is really useful when copying and moving files around using long paths. Using brace expansion can minimise the amount of typing and help avoid errors caused by typos too.

Another use of brace expansion since BASH v3.0 is the possibility of using ranges within the lists like so:

for foo in {1..10}
> do
> echo $foo
> done
1
2
3
4
5
6
7
8
9
10

Or alternatively with letters too:

echo {a..f}
a b c d e f

See the advanced bash scripting guide for more examples.

comments powered by Disqus