Recently, I discovered a great feature that most of recent Shells support. It is named brace expansion. I used it occasionally but without knowing how it behaves and what was its power.

Below is an example:

In this example, {like,love,hate} has a special meaning: it’s a list of String elements delimited by braces whose elements are expanded with the word it is attached with. As the output shows, once evaluated each String element creates a new word by replacing the list by its value.

Ok, that’s interesting but could it be used with a concrete example? the answer is yes. Let’s say that you need to create several folders in a same directory. The simplest manner I was aware of was to move to the desired folder and then to use the mkdir command for each directory:

The previous sequence of commands can be written pretty quickly but requires fingers gymnastic using keyboard shortcuts. With brace expansion, the previous example can be easily one-lined:

# Nested brace expansion

Brace lists can be composed. For instance, the example above can be extended to create a hierarchy of folders quickly:

It will create the following folders in your home directory:

# Generating sequences

If you come from the imperative world (e.g. if you know for instance C or even used loops with Java), you are probably familiar with the 3 parameters loop control expression. You also know how boring it is to write, especially in Shell:

Using brace sequences, the writing is shorter and more readable:

The general syntax for a sequence expression is {START..END..INCREMENT} where START and END is a required integer or single character but INCREMENT an optional integer value (default to 1). Such an expression generates a sequence of integers or characters by INCREMENT step, starting from START to END included. This way, listing odd numbers between 9 and 17 is as simple as writing:

While enumerating the alphabet is not more complex:

# Limitations

1. A valid brace expansion must contain at least a comma or a sequence expression.
2. Variable expansion works inside a brace list but not inside a sequence expression.

In conclusion, brace expansion is a really powerful feature that can save you time when you have to create directories, apply permissions, etc. Besides, the good news is that it is supported by almost all recent Shells.