Making good use of brace expansion

repetition yul sotozaki
Credit: flickr / Yul Sotozaki

Brace expansion seems to be one of the shell tricks that lots of people overlook. It can come in very handy when you need to generate strings. Say you want to create a backup directory for each day of the work week, you might do it like this:

$ mkdir backup.{mon,tue,wed,thu,fri}
$ ls -ld backup*
drwxr-x--- 2 shs staff 4096 Mar 12 2015 backup.fri
drwxr-x--- 2 shs staff 4096 Mar 12 2015 backup.mon
drwxr-x--- 2 shs staff 4096 Mar 12 2015 backup.thu
drwxr-x--- 2 shs staff 4096 Mar 12 2015 backup.tue
drwxr-x--- 2 shs staff 4096 Mar 12 2015 backup.wed

The expansion matches up the text outside of the braces with each of the strings separated by commas within the braces. And, of course, you can remove the directories just as easily with rmdir backup.{mon,tue,wed,thu,fri} or with $ rm -rf backup.{mon,tue,wed,thu,fri} if you've put files in them.

If you want to list only the most recent three rotated messages files, you can use the expression {1..3} to select only the messages files that end in 1, 2, or 3.

$ ls -l /var/log/messages.{1..3}
-rw------- 1 root root 14070 Mar  7 22:49 /var/log/messages.1
-rw------- 1 root root 41984 Mar  1 00:17 /var/log/messages.2
-rw------- 1 root root 34717 Feb 21 23:04 /var/log/messages.3

You can use brace expansion multiple times in a command if you like. Both of the {a..z} expressions in this command runs through all 26 letters in the alphabet so you end up with a list of strings that run from aa to zz.

$ echo {a..z}{a..z}
aa ab ac ad ae af ag ah ai aj ak al am an ao ap aq ar as at au
av aw ax ay az ba bb bc bd be bf bg bh bi bj bk bl bm bn bo bp
bq br bs bt bu bv bw bx by bz ca cb cc cd ce cf cg ch ci cj ck
cl cm cn co cp cq cr cs ct cu cv cw cx cy cz da db dc dd de df
dg dh di dj dk dl dm dn do dp dq dr ds dt du dv dw dx dy dz ea
eb ec ed ee ef eg eh ei ej ek el em en eo ep eq er es et eu ev
ew ex ey ez fa fb fc fd fe ff fg fh fi fj fk fl fm fn fo fp fq
...

This may not be something you do every day, but it will save you a lot of time whenever you need to generate a pile of strings given a particular pattern. You might be surprised how often it turns out to be a very handy trick.

This article is published as part of the IDG Contributor Network. Want to Join?

To express your thoughts on Computerworld content, visit Computerworld's Facebook page, LinkedIn page and Twitter stream.
Related:
Windows 10 annoyances and solutions
Shop Tech Products at Amazon
Notice to our Readers
We're now using social media to take your comments and feedback. Learn more about this here.