Search code examples
bashif-statementpattern-matchingpartial

exact match using if statement ? does partial match as well need to do exact match


I have the following command in my script. It works fine with one exception; it also matches partial entries. I want the match to be exact.

a=mary jane uger dodo baba
b=mary
c=ma    

if [[ "$a" =~ "$b" ]] && [ -n "$1" ]; then
    echo it matches
else
    echo it does not match
fi

So no matter if in the if statement i use value $b or $c they both match. I want to ensure that the entry is fully match and not partially. So this should work and give exact match.

if [[ "$a" =~ "$b" ]]  

and this should not work partial match

if [[ "$a" =~ "$c" ]]

Can someone help please?

here is my exact code

if [[ "$a" =~ "$b" ]]; then
      echo something     
fi

Solution

  • z='\>'
    [[ $a =~ $b$z ]] # true
    [[ $a =~ $c$z ]] # false
    

    does bash support word boundary regular expressions?