Using Brace Bash Expansion

|^^|

source: http://www.ixbrian.com/blog/?m=201510

This post is all about the bash shell brace expansion.

The basics are you can put a list of items in braces, and the bash shell will expand them out, for example:

1

2

$ echo {dev,test,prod}app{01..04}

devapp01 devapp02 devapp03 devapp04 testapp01 testapp02 testapp03 testapp04 prodapp01 prodapp02 prodapp03 prodapp04

The {dev,test,prod} is just what it looks like, and the {01..04} means numbers 1-4 with a padded zero in front, and as you can see the shell expands it out with all of the possible combinations.

This can be helpful if you have a server naming convention and need to perform a task on a bunch of servers, but don’t want to have to type out all the server names, for example, to use SSH to check the /tmp filesystem:

1

for server in {dev,test,prod}app{01..04}; do echo $server; ssh -q $server df -m /tmp; done

{0..100} will expand to the numbers 0-100, but what if you wanted to count up by 5? No problem, just use {0..100..5}

1

2

$ echo {0..100..5}

0 5 10 15 20 25 30 35 40 45 50 55 60 65 70 75 80 85 90 95 100

You can also expand letters:

1

2

$ echo {a..z}

a b c d e f g h i j k l m n o p q r s t u v w x y z

You can use it to make multiple directories outside the directory you are in:

1

$ mkdir /tmp/{dir1,dir2,dir3}

This creates /tmp/dir1, /tmp/dir2, and /tmp/dir3

You could even go further with this by creating nested subdirectories:

1

mkdir /tmp/{dir1,dir2,dir3}/{subdir1,subdir2,subdir3}

That will create /tmp/dir1/subdir1, /tmp/dir1/subdir2, /tmp/dir1/subdir3, /tmp/dir2/subdir1, /tmp/dir2/subdir2, /tmp/dir2/subdir3, /tmp/dir3/subdir1, /tmp/dir3/subdir2, and /tmp/dir3/subdir3.

You can also use it to backup files easily:

1

cp testfile{.txt,.backup}

If your not sure what that one does, an easy way to test what it will do is to put an “echo” in front:

1

2

$ echo cp testfile{.txt,.backup}

cp testfile.txt testfile.backup

So we can see that “cp testfile{.txt,.backup}” will copy testfile.txt to testfile.backup.

What if we wanted to copy it to testfile.txt.backup? No problem:

1

cp testfile.txt{,.backup}

Putting a comma at the beginning of the brace expansion causes it to expand on to the previous word in front of the brace. If we echo it out we can see what it is doing:

1

2

$ echo cp testfile.txt{,.backup}

cp testfile.txt testfile.txt.backup

Bash brace expansion is one of those things that is easy to pick up and can save you a bunch of time typing!

eof