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

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 !


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

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


$ item='foobar baz'; pat=".+bar baz"; if [[ $item =~ $pat ]]; then echo OK; fi
  • pat="^.+bar baz$" – Costas Dec 24 '15 at 18:13
  • @Stphane check edits – heemayl Dec 24 '15 at 18:24
  • @heemayl Thank you for your time / code review .. No error anymore ! But I don't get the ok :p – Stphane Dec 24 '15 at 18:25
  • @Stphane yes..check edits..which version of bash you have? – heemayl Dec 24 '15 at 18:28
  • @heemayl GNU bash, version 4.3.30(1)-release (x86_64-pc-linux-gnu) – Stphane Dec 24 '15 at 18:28

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.