Please enable JavaScript eh!

 ⌘ Web Mechanic ⌘ 

Bash Scripting


Expansions

Brace Expansion

Brace expansion is a mechanism by which arbitrary strings may be generated.

It provides a way of saving typing when strings have prefixes or suffixes of each other.

In English, on my iMac, that means when you have a string enclosed in braces {}, you have several options.

On some systems, this may not be enabled. To check, enter the following command:

set -o | grep brace
which should return
braceexpand    	on
If it doesn't, enter the following command to enable it:
set -B

Now for some fun ...

echo jam{a,e,i,o,u}rt
jamart jamert jamirt jamort jamurt

That generated some arbitrary strings beginning with jam and ending with rt, with the letters a e i o u added between them.

Several commands can be 'expanded' this way:

mkdir jam{a,e,i,o,u}rt
... resulted in 5 new directories in my current directory.


like this.

But no worries. We can also delete those same directories:

rmdir jam{a,e,i,o,u}rt

Brace expansions may be nested. The results of each expanded string are not sorted; left to right order is preserved.

echo {a..d}{0..5}
a0 a1 a2 a3 a4 a5 b0 b1 b2 b3 b4 b5 c0 c1 c2 c3 c4 c5 d0 d1 d2 d3 d4 d5
or a sequence of 6-letter strings... (a LOT of them)
echo {A..D}{0..5}{b..e}{6..9}{F..J}{8..3}

We can also use it to generate sequences of letters or numbers:

echo {a..m}
a b c d e f g h i j k l m
echo {N..Z}
N O P Q R S T U V W X Y Z
echo {33..42}
33 34 35 36 37 38 39 40 41 42
even numbers with leading 0s ...
echo {00..12}
00 01 02 03 04 05 06 07 08 09 10 11 12
or formatted ...
printf '%s\n' {00..12}
00
01
02
03
04
05
06
07
08
09
10
11
12
or staggered sequential (with leading 0).
echo {00..22..2}
00 02 04 06 08 10 12 14 16 18 20 22

Parameter Expansion | Tilde Expansion