Saving Keystrokes With Brace Expansion

Bash is a wonderful fully featured shell that provides a multitude of ways to cut back on your keystrokes. One of my favorite features, which I don’t see used often enough, is brace expansion. Simply put, brace expansion lets you specify multiple similar arguments without retyping the commonalities.

With this handy feature, you can do a multitude of things. You can make a backup copy of a file:

cp /etc/mpd.conf{,~}  #Same as cp /etc/mpd.conf /etc/mpd.conf~

Then you can restore that file:

cp /etc/mpd.conf{~,}  #Same as cp /etc/mpd.conf~ /etc/mpd.conf

Obviously, it doesn’t stop here. You can make a whole directory structure:

mkdir -p /squashed/{usr,opt}/{rw,ro}  #Same as mkdir -p /squashed/usr/rw /squashed/usr/ro /squashed/opt/rw /squashed/opt/ro

Bash will expand ranges as well. You can create a zero padded range like so:

echo {000..100}  #Will print 000 001 002 003 ... 097 098 099 100

Ranges aren’t limited to being numerical. Better yet, expressions can be the preamble and postscript to each other.

echo {0..9}{A..Z}   #Prints 260 strings!

If you really use your noodle you can nest expressions, though I’ve personally not come across a situation where this has been needed (yet).

2 Responses to “Saving Keystrokes With Brace Expansion”

  1. 1 Alex Reisner December 3, 2009 at 10:10 pm

    Wow–that’s pretty nice. I had no idea. Something that’s saved me some keystrokes recently is “cd -” to go back to the last directory. But you probably knew that.

  2. 2 Simon January 4, 2010 at 12:31 am

    Really usefull tip, was already useing braces to cut down some typing but didn’t know about this usage. thanks alot.

Leave a Reply

Fill in your details below or click an icon to log in: Logo

You are commenting using your account. Log Out /  Change )

Google photo

You are commenting using your Google account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s

%d bloggers like this: