đź“ť Edit page
âž• Add page
Pattern matching
Check if a string matches a pattern
Related
Plain text matching
Equality
Use single or double equals sign - the same in newer shells.
[[ VARIABLE == VALUE ]]
e.g.
[[ "$NAME" == "Joe" ]]
Starts with
Test using ==
and a pattern with a *
globstar and no quotes.
# macOS
OSTYPE=darwin19.0
[[ "$OSTYPE" == darwin* ]] && echo 'Yes' || echo 'No'
# Yes
Contains
A more specific case of pattern matching. Use =
or ==
.
[[ VALUE == *NEEDLE* ]]
e.g.
MSG="I like dogs, don't you?"
[[ MSG == *dog* ]] && echo 'Yes' || echo 'No'
Yes
Note lack of quotes so that *
gets expanded for the check. In this case *
does not have to do with paths like it usually does.
GREETING='Hello, world'
[[ "$GREETING" = *lo* ]] && echo 'Match' || echo 'No match'
Match
Check if a string is in your OS type.
[[ "$OSTYPE" = *darwin* ]] && echo 'I'm a mac' || echo 'I'm not a mac'
Regex pattern matching
Use =~
and a regex pattern.
[[ STRING =~ PATTERN ]]
Be sure to not use quotes on the pattern or you’ll get unexpected behavior.
Basic
No special functionality. Just string contains.
[[ "$PATH" =~ ruby ]] && echo 'Yes' || echo 'No'
Starts with
FIRST=abc
SECOND=def
[[ "$FIRST" =~ '^d' ]] && echo 'Match' || echo 'No match'
# No match
[[ "$SECOND" =~ '^d' ]] && echo 'Match' || echo 'No match'
# Match
[[ "main" =~ ^m ]] && echo 'Yes' || echo 'No'
# Yes
[[ "$PATH" =~ ^/ ]] && echo 'Yes' || echo 'No'
List
FRUIT='apple'
[[ "$FRUIT" =~ banana|apple|orange ]] && echo 'Yes' || echo 'No'
# Yes
Negate:
if [[ ! "$FRUIT" =~ banana|apple|orange ]]; then
echo 'Your fruit is not one of the allowed fruit'
exit 1
fi
Pattern as a variable
Store your regex pattern as a variable and then use it later.
PATTERN='banana|apple|orange'
FRUIT='apple'
[[ "$FRUIT" =~ "$PATTERN" ]] && echo 'Yes' || echo 'No'
# Yes