13

Look at this if block:

#!/bin/bash

str="m.m"
if [[ "${str}" =~ "m\.m" ]]; then
    echo "matched"
else
    echo "not matched"
    exit 1
fi

exit 0

This should print "matched", but it doesn't. Where am I going wrong?

1 Answer 1

25

You need to remove the quoting in the regex match.

if [[ ${str} =~ m\.m ]]; then

From the bash man page:

[...] 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 expres‐ sion and matched accordingly (as in regex(3)). The return value is 0 if the string matches the pattern, and 1 otherwise. If the regular expression is syntactically incorrect, the conditional expression's return value is 2. If the shell option nocasematch is enabled, the match is performed without regard to the case of alphabetic characters. Any part of the pattern may be quoted to force it to be matched as a string.

So with the quotes, you're using good-old string matching.

If you need spaces in the pattern, just escape them:

str="m   m"
if [[ ${str} =~ m\ +m ]]; then
3
  • but with no double quote, we can not use space character in regex pattern. Is there any solution for that? Feb 19, 2012 at 17:55
  • 1
    Space should be escaped like \ . Feb 19, 2012 at 17:56
  • If I want to find a string that ends with a dynamic number should use ${str} =~ "needle"[0-9]{1} or should I use ${str} =~ needle[0-9]{1}?
    – mgutt
    Aug 1, 2019 at 22:41

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .