Thursday, February 21, 2013

Extended pattern matching in Bash

While writing scripts in Bash I have found myself needing a more expressive pattern matching for filename expansion, than just the usual "*, ?" and "[]" characters.

When I was looking for a way to accomplish what I wanted to do, I found out that Bash actually contains more advanced pattern matching capabilities, as well as several other interesting features that come disabled by default in most Linux distributions.

The shopt command allows us to query the current status and enable / disable Bash optional behaviours. To manage the extended matching operators, we need to enable the extglob option.

With no options, the shopt command retrieves the current status of the provided Bash option:

$ shopt extglob
extglob        off

Use -s to enable the Bash option you are interested in:

$ shopt -s extglob
$ shopt extglob
extglob        on

Now you can use the extended pattern matching operators, as explained in the Bash reference manual.

References