A chronological documentation test project, nothing serious, really!

20 May 2007 Using brace expansion in bash

Posted by

Everyone has done one of the following to make a quick backup of a file:

$ cp filename filename-old
$ cp filename-old filename

These seem fairly straightforward, what could possibly make them more efficient? Let’s look at an example

$ cp filename{,-old}
$ cp filename{-old,}
$ cp filename{-v1,-v2}

Brace expansion can take place anywhere in your command string, can occur multiple times in a line and even be nested. Brace expansion expressions are evaluated left to right. Some examples

$ touch a{1,2,3}b
$ touch {p2,pv,av,}p
$ ls /usr/{,local/}{,s}bin/jojo

The first example will create three files called a1b, a2b and a3b In this case, the preamble is prepended and the postscript is appended to each string within the curly braces. The second example contains no preamble, so the postscript is appended to each string as before, creating p2p, pvp, avp and simply p The last string in the second example is empty, so p is appended to nothing and becomes just p The third example shows multiple brace expansions on the same line and expands to this

$ ls /usr/bin/jojo /usr/sbin/jojo /usr/local/bin/jojo /usr/local/sbin/jojo


Comments are closed.