The man page for bash has this to say about the =~ operator:

An additional binary operator, =~, is available, with the same precedence as == and !=. When it is used, the string to the right of the operator is considered an extended regular expression and matched accordingly (as in regex(3))

However, I'm finding that even trivial REs don't appear to work. Here is my use case example:

[[ "$n" =~ 'llo' ]] && echo yes || echo no   # <-- yes
[[ "$n" =~ 'llo$' ]] && echo yes || echo no  # <-- no

Given that $ is a standard RE indicator for EOL, why does the second comparison return "no"?

  • 1
    remove the quotes around the RE – iruvar Oct 15 '15 at 11:45
  • @1_CR thank you. For my example your suggestion works. How would one include a space in the RE pattern without the quotes? Example n='hello world'; [[ "$n" =~ 'lo world$' ]] – roaima Oct 15 '15 at 11:51
  • 1
    I would stick the RE into a variable and use it, like so var='lo world$';[[ "$n" =~ $var ]] – iruvar Oct 15 '15 at 11:53
  • 1
    @roaima, [[ $n =~ "lo world"$ ]] -- the literal chars are in quotes, the RE metachars are not – glenn jackman Oct 15 '15 at 13:39

You didn't read the man page carefully, it also said:

Any part of the pattern may be quoted to force the quoted portion to be matched as a string.

So the $ in your string means the literal dollar sign instead of end of string. Moving the $ from the string to make it work:

$ [[ "$n" =~ 'llo'$ ]] && echo yes || echo no
| improve this answer | |
  • Oh I definitely read it carefully. Clearly just not carefully enough, thank you. More usefully, I don't think I'd registered the intent of that sentence. My reasoning was that an RE is a string, so quoting it would prevent the shell trying to evaluate variables, split at spaces, etc. – roaima Oct 15 '15 at 11:56
  • @roaima: glob+split wasn't performed inside [[...]]. – cuonglm Oct 15 '15 at 11:59
  • 2
    The bash manual is VERY densely packed with information: every sentence is meaningful. You definitely have to be on your toes and read and re-read to catch the meaning. – glenn jackman Oct 15 '15 at 12:59

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.