Bash Extended Globbing
Wildcards in bash are referred to as pathname expansion. Pathname expansion is also sometimes referred to as globbing. Pathname expansion "expands" the "*", "?", and "[...]" syntaxes when you type them as part of a command, for example:
$ ls *.jpg # List all JPEG files $ ls ?.jpg # List JPEG files with 1 char names (eg a.jpg, 1.jpg) $ rm [A-Z]*.jpg # Remove JPEG files that start with a capital letterA subtle point about pathname expansion that is not often understood is that it is done by bash and not by the operating system or by the program that is being run. The program never sees the wildcards, bash substitutes the expansion into the command line before running the program. This is rarely important except when you're writing code and calling exec() and friends: if you don't execute the program via bash any wildcards in the command line that you pass to exec() won't get expanded.
But these are not the only forms of wildcards supported by bash. The other forms are referred to as extended globbing and you must enable them before you can use them:
$ shopt -s extglobExtended globbing as described by the bash man page:
?(pattern-list) Matches zero or one occurrence of the given patterns *(pattern-list) Matches zero or more occurrences of the given patterns +(pattern-list) Matches one or more occurrences of the given patterns @(pattern-list) Matches one of the given patterns !(pattern-list) Matches anything except one of the given patternsHere a pattern-list is a list of items separated by a vertical bar "|" (aka the pipe symbol). If you look at these you can see why the leading character was chosen as it matches what is used in regular expression syntax:
Bash Regular Expression ?(pattern-list) (...|...)? *(pattern-list) (...|...)* +(pattern-list) (...|...)+ @(pattern-list) (...|...) [@ not a RE syntax] !(pattern-list) "!" used as for negative assertions in RE syntaxWell, except for the "@" character you can see why...
For example, to list all the JPEG and GIF files that start with either "ab" or "def" you could do:
$ ls +(ab|def)*+(.jpg|.gif)Of course you could also do this without extended globbing:
# ls ab*.jpg ab*.gif def*.jpg def*.gif
To list all the files that match the regular expression "ab(2|3)+.jpg" you could do:
$ ls ab+(2|3).jpgNow that's something you can't do with regular globbing. Note: this matches files like ab2.jpg, ab3.jpg, ab2222.jpg, ab333.jpg, etc.
However, probably the most interesting extended globbing syntax is the "!(...)" syntax for matching everything except (ie not matching). But, be careful, this doesn't always do what you might expect. For example, let's list all the files that aren't JPEGs or GIFs. One's first thought might be something like this:
$ ls *!(.jpg|.gif) # wrong, Wrong, WRONGBut that doesn't work because the ".jpg" and the ".gif" of any file's name end up getting matched by the "*" and the null string at the end of the file name is the part that ends up not matching the "!(...)" pattern. The correct syntax is:
$ ls !(*.jpg|*.gif)
For a more complex negation example, let's go back to the first example and list all the files that aren't JPEG or GIF files and start with either "ab" or "def". This is actually quite simple, we just take the first example and nest it inside of "!(...)":
$ ls !(+(ab|def)*+(.jpg|.gif))Of course, like complex regular expressions, this will be completely incomprehensible 10 minutes after you write it.
Mitch Frazier is an Associate Editor for Linux Journal.
Realizing the promise of Apache® Hadoop® requires the effective deployment of compute, memory, storage and networking to achieve optimal results. With its flexibility and multitude of options, it is easy to over or under provision the server infrastructure, resulting in poor performance and high TCO. Join us for an in depth, technical discussion with industry experts from leading Hadoop and server companies who will provide insights into the key considerations for designing and deploying an optimal Hadoop cluster.
Sponsored by AMD
Built-in forensics, incident response, and security with Red Hat Enterprise Linux 6
Every security policy provides guidance and requirements for ensuring adequate protection of information and data, as well as high-level technical and administrative security requirements for a system in a given environment. Traditionally, providing security for a system focuses on the confidentiality of the information on it. However, protecting the data integrity and system and data availability is just as important. For example, when processing United States intelligence information, there are three attributes that require protection: confidentiality, integrity, and availability.
Learn more about catching the bad guy in this free white paper.
Sponsored by DLT Solutions
| Designing Electronics with Linux | May 22, 2013 |
| Dynamic DNS—an Object Lesson in Problem Solving | May 21, 2013 |
| Using Salt Stack and Vagrant for Drupal Development | May 20, 2013 |
| Making Linux and Android Get Along (It's Not as Hard as It Sounds) | May 16, 2013 |
| Drupal Is a Framework: Why Everyone Needs to Understand This | May 15, 2013 |
| Home, My Backup Data Center | May 13, 2013 |
- Designing Electronics with Linux
- New Products
- Linux Systems Administrator
- Senior Perl Developer
- Technical Support Rep
- UX Designer
- Making Linux and Android Get Along (It's Not as Hard as It Sounds)
- Dynamic DNS—an Object Lesson in Problem Solving
- Web & UI Developer (JavaScript & j Query)
- Using Salt Stack and Vagrant for Drupal Development
- Reply to comment | Linux Journal
6 hours 11 min ago - Dynamic DNS
6 hours 45 min ago - Reply to comment | Linux Journal
7 hours 43 min ago - Reply to comment | Linux Journal
8 hours 34 min ago - Not free anymore
12 hours 36 min ago - Great
16 hours 23 min ago - Reply to comment | Linux Journal
16 hours 31 min ago - Understanding the Linux Kernel
18 hours 45 min ago - General
21 hours 15 min ago - Kernel Problem
1 day 7 hours ago
Enter to Win an Adafruit Pi Cobbler Breakout Kit for Raspberry Pi

It's Raspberry Pi month at Linux Journal. Each week in May, Adafruit will be giving away a Pi-related prize to a lucky, randomly drawn LJ reader. Winners will be announced weekly.
Fill out the fields below to enter to win this week's prize-- a Pi Cobbler Breakout Kit for Raspberry Pi.
Congratulations to our winners so far:
- 5-8-13, Pi Starter Pack: Jack Davis
- 5-15-13, Pi Model B 512MB RAM: Patrick Dunn
- 5-21-13, Prototyping Pi Plate Kit: Philip Kirby
- Next winner announced on 5-27-13!
Featured Jobs
| Linux Systems Administrator | Houston and Austin, Texas | Host Gator |
| Senior Perl Developer | Austin, Texas | Host Gator |
| Technical Support Rep | Houston and Austin, Texas | Host Gator |
| UX Designer | Austin, Texas | Host Gator |
| Web & UI Developer (JavaScript & j Query) | Austin, Texas | Host Gator |
Free Webinar: Hadoop
How to Build an Optimal Hadoop Cluster to Store and Maintain Unlimited Amounts of Data Using Microservers
Realizing the promise of Apache® Hadoop® requires the effective deployment of compute, memory, storage and networking to achieve optimal results. With its flexibility and multitude of options, it is easy to over or under provision the server infrastructure, resulting in poor performance and high TCO. Join us for an in depth, technical discussion with industry experts from leading Hadoop and server companies who will provide insights into the key considerations for designing and deploying an optimal Hadoop cluster.
Some of key questions to be discussed are:
- What is the “typical” Hadoop cluster and what should be installed on the different machine types?
- Why should you consider the typical workload patterns when making your hardware decisions?
- Are all microservers created equal for Hadoop deployments?
- How do I plan for expansion if I require more compute, memory, storage or networking?



Comments
Dangerous example for rm
In bash,
$ rm [A-Z]*.jpg # Remove JPEG files that start with a capital letterremoves [a-y]*.jpg files too if LANG is set to en_US! The z*.jpg files are ignored, because the collation order is AaBb..Zz. Bash documents that they'll use the collation order. Personally, I think they need to recognize that sorting for people and sorting for computers is different, and that upper case and lower ranges should always be separate for globbing. Admins are coding for computers, not people.
Not quite
Actually, on my machine the order seems to be aAbB...zZ.
#~/mytest> ls [a-z]*
a A b B z
#~/mytest> ls [A-Z]*
A b B z Z
rm command's dangers
A similar discussion is found here. Here, filenames having space in them, are not handled properly.
Same Results
I could get the same result with :
(which I think it's much convenient / much easier to write)
- ls -alt [a-z]*.{jpg,gif}
- ls -alt [a-z]?.{jpg,gif}
- ls -alt t{[0-9]*,[a-z]*}.{jpg,gif}
hope this helps
Not really
This:
ls -alt [a-z]*.{jpg,gif}lists jpg/gif files that start with any lower case letter followed by any number of other characters.
This:
ls -alt [a-z]?.{jpg,gif}lists jpg/gif files start with any lower case letter followed by any single character.
This:
ls -alt t{[0-9]*,[a-z]*}.{jpg,gif}lists jpg/gif files that start with the letter t followed by either a digit or a lower case letter and then followed by any number of other characters.
Although the first two will list files that start with "ab" or "def", they also list many other files. Not even sure what your last example is meant to compare to since I don't have any examples that list files starting with the letter t.
The point of the examples is not to show the "simplest" way to perform the examples themselves, but rather to illustrate extended globbing.
Mitch Frazier is an Associate Editor for Linux Journal.
similar effect with another trick
That:
$ ls +(ab|def)*+(.jpg|.gif)
can be done in bash NOT with:
$ ls ab*.jpg ab*.gif def*.jpg def*.gif
but more effieciently with:
$ ls {ab,def}*.{jpg,gif}
Though you missed the point. 1st syntax is different from 2nd (and 3rd) in that in 2nd and 3rd cases "ls" would complain if some of the patterns are not found. (e.g. "ab*.jpg" not found) while in first case bash would properly expand the expression listing only matching files.
Only if you squint
True, they do behave differently if there are no matching files. And yes the "syntax" is different since they are written differently, what you probably mean is that the "semantics" are different because they do not act the same if the expansion fails. So, when I stated Of course you could also do this without extended globbing, it was not my intention to imply that the two forms were exactly the same in all instances. The point here was to illustrate how to use extended globbing and not to provide a comparison between the different ways to list jpg/gif files that start with "ab" or "def".
Mitch Frazier is an Associate Editor for Linux Journal.