Brace expansion (was: web comic)

Ben Scott dragonhawk at gmail.com
Fri Sep 21 11:49:45 EDT 2012


On Fri, Sep 21, 2012 at 11:32 AM, Ben Scott <dragonhawk at gmail.com> wrote:
> I use brace expansion *all the time*.  It's very handy for
> manipulating groups of files with similar names.

  To expand[[1] on this a bit, for those who aren't familiar with it:

  Brace expansion is a little bit like glob pattern expansion, in that
it replaces words in a command line with a larger number of words[2],
and then processes the resulting expanded command line.  But unlike
glob pattern expansion, it doesn't match file names, it just generates
strings from a pattern.

  A construct of the form

	ding{for,bar,baz}dong

will be expanded to

	dingfoodong dingbardong dingbazdong

by the shell[3].  So one can do something like

	mv foo.{c,h,o} ../bar/

  One can also specify sequences.  This

	X{a..c}Y

expands to

	XaY XbY XcY

and this

	a{3..6}b

expands to

	a3b 346 a5b

Multiple brace expansions in the same word will multiply.  Separate
words are expanded separately.  So this

	X{a..c}Y A{1..3}B

expands to this

	XaY XbY XcY A1B A2B A3B

while this

	X{a..c}Y{1..3}Z

expands to

	XaY1Z XaY2Z XaY3Z XbY1Z XbY2Z XbY3Z XcY1Z XcY2Z XcY3Z

  As Mr. Alan Johnson points it, it's functionally equivalent to a
"for foo in ... " construct, optionally combined the seq(1) command,
but it's much more concise to type or read, and it's often faster.

  Brace expansion is also available in some other contexts.  Mr. Rosen
provides the tip that curl(1) will expand braces internally.  This
should be faster still than doing it in the shell, and can solve
problems with unreasonably long command lines.  One has to escape the
braces to prevent the shell from expanding them:

	curl 'http://www.example.com/{foo,bar}.png'

  If one left out the quotes, the shell would expand it to:

	curl http://www.example.com/foo.png http://www.example.com/bar.png

which would still work for this example, but not when there are
256^2*4 expansions.  :)

-- Ben

[1] I swear this pun wasn't intended.
[2] Technically speaking, it could also expand to the same number, for
degenerate cases.
[3] Well, Bash, at least, and I think some others.


More information about the gnhlug-discuss mailing list