You want to test a string not for a literal match, but to see if it fits a pattern.
For example, you want to know if a file is named like a JPEG file might be named.
Use the double-bracket compound statement in an if statement to enable shell-style pattern matches on the righthand side of the equals operator:
1 |
if [[ "${MYFILENAME}" == *.jpg ]] |
The double-brackets is a newer syntax (bash version 2.01 or so). It is not the oldfashioned [ of the test command, but a newer bash mechanism.
It uses the same operators that work with the single bracket form, but in the double-bracket syntax the equal sign is a more powerful string comparator.
The equal sign operator can be a single equal sign or a double equals as we have used here.
They are the same semantically. We prefer to use the double equals (especially when using the pattern matching) to emphasize the difference, but it is not the reason that we get pattern matching—that comes from the double-bracket compound statement.
The standard pattern matching includes the * to match any number of characters, the question mark (?) to match a single character, and brackets for including a list of possible characters.
Note that these resemble shell file wildcards, and are not regular expressions.
Don’t put quotes around the pattern if you want it to behave as a pattern.
If our string had been quoted, it would have only matched strings with a literal asterisk as the first character.
There are more powerful pattern matching capabilities available by turning on some additional options in bash.
Let’s expand our example to look for filenames that end in either .jpg or .jpeg. We could do that with this bit of code:
1 2 3 4 |
shopt -s extglob if [[ "$FN" == *.@(jpg|jpeg) ]] then # and so on |
The shopt -s command is the way to turn on shell options. The extglob is the option dealing with extended pattern matching (or globbing).
With this extended pattern matching we can have several patterns, separated by the | character and grouped by
parentheses.
The first character preceding the parentheses says whether the list should match just one occurrence of a pattern in the list (using a leading @) or some other criteria.
Table 6-4 lists the possibilities (see also “extglob Extended Pattern-Matching Operators” in Appendix A ).
Table 6-4. Grouping symbols for extended pattern-matching
Grouping | Meaning |
@( … )
*( … ) +( … ) ?( … ) !( … ) |
Only one occurrence
Zero or more occurrences One or more occurrences Zero or one occurrences Not these occurrences, but anything else |
Matches are case sensitive, but you may use shopt -s nocasematch (in bash versions 3.1+) to change that.
This option affects case and [[ commands.