12

I know I can use grep, awk etc, but I have a large set of bash scripts that have some conditional statements using =~ like this:

#works
if [[ "bar" =~ "bar" ]]; then echo "match"; fi

If I try and get it to do a logical OR, I can't get it to match:

#doesn't work
if [[ "bar" =~ "foo|bar" ]]; then echo "match"; fi

or perhaps this...

#doesn't work
if [[ "bar" =~ "foo\|bar" ]]; then echo "match"; fi

Is it possible to get a logical OR using =~ or should I switch to grep?

simon
  • 1,840
  • 2
  • 18
  • 34

1 Answers1

16

You don't need a regex operator to do an alternate match. The [[ extended test operator allows extended pattern matching options using which you can just do below. The +(pattern-list) provides a way to match one more number of patterns separated by |

[[ bar == +(foo|bar) ]] && echo match

The extended glob rules are automatically applied when the [[ keyword is used with the == operator.

As far as the regex part, with any command supporting ERE library, alternation can be just done with | construct as

[[ bar =~ foo|bar ]] && echo ok
[[ bar =~ ^(foo|bar)$ ]] && echo ok

As far why your regex within quotes don't work is because regex parsing in bash has changed between releases 3.1 and 3.2. Before 3.2 it was safe to wrap your regex pattern in quotes but this has changed in 3.2. Since then, regex should always be unquoted.

You should protect any special characters by escaping it using a backslash. The best way to always be compatible is to put your regex in a variable and expand that variable in [[ without quotes. Also see Chet Ramey's Bash FAQ, section E14 which explains very well about this quoting behavior.

Inian
  • 80,270
  • 14
  • 142
  • 161
  • 1
    +1 This is great to know, thanks! But I wanted to have the flexibility of a regex that I can using in a variable. An answer has been given in a comment, I'm waiting for the poster to turn it into an answer. – simon Jun 04 '19 at 19:11