Cartesian products in Bash

Here’s a handy thing you can do in Bash: calculate the Cartesian product of two sets.

E.g.

echo {A,B,C}{A,B,C}

gives

AA AB AC BA BB BC CA CB CC

i.e. it’s every possible permutation of two elements from the two sets.

A --- A
  \ /
B -x- B
  / \
C --- C

(Thanks to Bill Hails for the diagram!)

This can be a useful tool for quickly figuring things out in various situations. For example, I wanted to write some tests for a feature that allowed users to set two configuration options to one of three values. Bash made it easy to list out the possible permutations I needed to cover in the tests.

You can control the number of elements in each permutation by the number of lists you give to Bash:

echo {A,B}{A,B}{A,B}
AAA AAB ABA ABB BAA BAB BBA BBB

Or use different sized lists that may or may not share elements:

echo {A,B}{A,B,C,D,E}
AA AB AC AD AE BA BB BC BD BE
echo {1,2}{A,B,C,D,E}
1A 1B 1C 1D 1E 2A 2B 2C 2D 2E

Bash also provides a nice syntax for making a list from a range, which works with numbers or letters:

echo {A..C}{A..D}
AA AB AC AD BA BB BC BD CA CB CC CD
echo {1..5}{A..C}
1A 1B 1C 2A 2B 2C 3A 3B 3C 4A 4B 4C 5A 5B 5C

It’s useful to have this helper immediately available on a terminal.


View post: Cartesian products in Bash