<<< Back to Tips Index

20 May 2015

www.shellscript.sh has an entire tutorial on Shell Scripting

Generating Sequences in Bash

A useful but underused feature of the Bash shell is called Brace Expansion.

It takes a few different forms, but basically, anything within the { braces } is expanded, either as a list ({apples,oranges,bananas}), a numerical sequence ({1..10}), or characters ({a..z}). TL;DR. You can stop reading here and you'll still have got a powerful feature. There is a little bit more to it, though. Nothing difficult, but there are a few details to understand if you're going to get the best out of them.

Numerial Expansion

This is probably the easiest, and it's simple enough to just show by example:

$ echo {1..10}          # Count from 1 to 10
1 2 3 4 5 6 7 8 9 10
$ echo {1..10..2}       # Count from 1 to 10 in steps of 2
1 3 5 7 9
$ echo {1..10..3}       # Count from 1 to 10 in steps of 3
1 4 7 10
$ # Note on this one that it automatically knows to count downwards:
$ echo {10..1}          # Count from 10 to 1
10 9 8 7 6 5 4 3 2 1
$ echo {10..1..-2}          # Count from 10 to 1 in steps of 2
10 8 6 4 2
$ echo {10..1..-3}          # Count from 10 to 1 in steps of 3
10 7 4 1
$ 

It will also do zero-padding, if you put a zero in front of either the "from" or "to" numbers.:

$ echo {010..10000..1000}    # Count from 10 to 10,000 in steps of 1,000
00010 01010 02010 03010 04010 05010 06010 07010 08010 09010
$ 

In this example, because the target is 10,000, it pads to 5 digits, even though it only gets as high as 9,010 because 10,010 is higher than the target number.

Character Expansion

This only works on single characters, and I'd be inclined to keep it to simple ASCII text for predictability (does "漢語" come before or after "華語"?), but for simple character expansion, it works the same as the numerical example:

$ echo {a..z}        # The basic alphabet
a b c d e f g h i j k l m n o p q r s t u v w x y z
$ echo {a..z..2}     # In steps of 2
a c e g i k m o q s u w y
$ echo {z..a..4}     # Counting down, in steps of 4
z v r n j f b
$ echo {A..z}        # ASCII goes "A-Z" then "a-z", with a few extras between:
A B C D E F G H I J K L M N O P Q R S T U V W X Y Z [  ] ^ _ ` a b c d e f g h i j k l m n o p q r s t u v w x y z
$ 

Expanding Lists

The third form of brace expansion is the expansion of lists, such as:

$ printf "I love the %s\n" {users,admins,developers,dbas}
I love the users
I love the admins
I love the developers
I love the dbas
$ 

This form is covered in the Expanding Lists tip.

Invest in your career. Buy my Shell Scripting Tutorial today:

 

Steve's Bourne / Bash shell scripting tips
Share on Twitter Share on Facebook Share on LinkedIn Share on Identi.ca Share on StumbleUpon
Join the Facebook page for more tips and tricks:


Buy my Shell Scripting Tutorial

(Free Sample)
(more info)

$9.99 US Dollars

£4.99 UK Pounds

€6.99 Euros