Testing with Pattern Matches

Problem

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.

Solution

Use the double-bracket compound statement in an if statement to enable shell-style pattern matches on the righthand side of the equals operator:

if [[ "${MYFILENAME}" == *.jpg ]]

Discussion

The double-brackets is a newer syntax (bash version 2.01 or so). It is not the old-fashioned [ 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 ...

Get bash Cookbook now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.