Sage-Code Laboratory
index<--

Braces Expansion

In Maj there is a special feature useful to simplify the code. This notation is simple and intuitive. You can use braces { ... } to generate a bunch of numbers and combine a number with a string to create a series of strings.

Notes:

  1. Brace expansion is happening before any other expansion. Therefore it can be used inside a command expansion. This is a useful way to create new commands dinamicly.
  2. You must use double quotes for "{" and "," or ";" if you want these to be present in the generated string. If branch expansion is not correct, the string pattern will remain unmodified.
  3. Symbol "$" must be escaped using "\" to be included in string as is otherwise will be interpreted as value placeholder and may be raising an error.

Enumerated vlaues

You can produce a series of strings by using an enumeration of values separated by comma and enclosed in braces like this: {one,two,three}.

Console
>bash
$ echo file-{one,two,three}.sh
file-one.sh file-two.sh file-three.sh
$
$ echo "\${"{a,b,c}{"[1]","[2]"}"};" 
${a[1]}; ${a[2]}; ${b[1]}; ${b[2]}; ${c[1]}; ${c[2]};
$

Range generators

You can generate a series of numbers in ascenting order or descenting. You can start from any number and end with greater or less number. You can also use a ratio different than 1. Also you can generate alphabet characters.

Examples
# range generator
echo {1..10}
echo {1..20..2}
echo {30..1..3}
echo {a..f}
Console
~/bash-repl$ bash the-range.sh
1 2 3 4 5 6 7 8 9 10
1 3 5 7 9 11 13 15 17 19
30 27 24 21 18 15 12 9 6 3
a b c d e f
~/bash-repl$ 

String patterns

You can combine a string pattern with range. This works with quoted strings or simple characters. The pattern is repeated using a range. You can use this trick to generate file names or key values that you need to loop over.

Console
>bash
$ echo a{1..3}x
a1x a2x a3x
$

Cartezian patterns

You can combine two or more ranges. This trick will create a combination of values. You can combine a string pattern with a cartezian range. You could use this to generate values for a 2d matrix.

Console
>bash
$ echo {a..c}{1..3}
a1 a2 a3 b1 b2 b3 c1 c2 c3
$

Computed ranges

You can generate a range using variable bounderies. Also, you can use a ration parameter to create a series of numbers. If the upper limit is less than the lower limit the range is decremental.

Console
>bash
$ min=4; max=20
$
$ echo a{$min..$max..2}
a4 a6 a8 a10 a12 a14 a16 a18 a20
$
$ echo {$max..$min..2}
$ 20 18 16 14 12 10 8 6 4
$

Read next: Arrays & Maps