Main menu

Post navigation

Bash shell expansion

Operations in the shell very often involve repeating yourself or working with
sets or ranges of information. This is where the various kinds of expansion in
the shell are most useful, for generating a large number of shell tokens using
a compact syntax. I’ll discuss two types here: filename expansions, which will
be familiar to most shell users; and brace expansions, which seem to be in less
common usage.

Filename expansions (globs)

The most commonly seen type of filename expansion in Bash is the * wildcard,
which can be used to match lists of files in any directory, whether through
complete listings or partial matches:

However, there are two other types of filename expansions. Firstly, you can
match single characters rather than ranges of characters with a question mark:

$ ls ?.txt
a.txt b.txt c.txt d.txt

You can further restrict this by matching only a single character in a
specified group of characters, or within a range:

$ ls [ac].txt
a.txt c.txt
$ ls [a-c].txt
a.txt b.txt c.txt

These can be useful in very large directories to only view files starting with
a nominated letter or number, or range of letters or numbers.

Brace expansion

Brace expansion is a little different, as it generates shell tokens that don’t
necessarily correspond to existing files. This allows you to expand a single
general form into a lot of space-delimited specific tokens. This is probably
best explained with examples. First of all, you can define the expansions you
want with comma separation: