Bash regular expression pattern matching spaces, within double brackets test, using “~=” operator

bashregular expressionstring

Simply said, I just can't find a way to match a variable against some pattern containing spaces.

Here is what I expected to work (echo 'ok' string)

item='foobar baz'
pat=".+bar baz"
if [[ "$item" =~ "$pat" ]] ; then
    echo ok
fi

Adding/removing quotes around $pat does not seem to make any difference.
I get those two erros below:

bash: conditional binary operator expected
bash: syntax error near `~='

Could someone please help me pointing out what I am doing wrong here ?
Should I put the pattern right away (without any quotes/double quotes, nor variable reference) ? If that is the case, then how can I put spaces in ? (using reg-exp matching, not an alternative)

Thank you !

Best Answer

The syntax error is self-explanatory i.e. you have used ~= instead of =~.

Regarding the Regex pattern, just use $pat (and also $item), being a shell builtin [[ can handle word splitting:

item='foobar baz'
pat=".+bar baz"
if [[ $item =~ $pat ]]; then
    echo ok
fi

When you use double quotes around $pat i.e. "$pat", the Regex tokens . and + are treated literally.

Example:

$ item='foobar baz'; pat=".+bar baz"; if [[ $item =~ $pat ]]; then echo OK; fi
OK
Related Question