Jack
Jack

Reputation: 5890

Understanding the difference between = and =~ operators in bash [[ ]]

  1. if [[ 23ab = *ab ]] ; then echo yes; fi

    Is the above code a regular expression?

    Please see the following:

  2. if [[ 23ab =~ [0-9]{1,2}ab ]] ; then echo yes; fi

So which line is a regex? If the first line is not a regex, why does it work when we are using *? If it is, but when we instead of =~ just using =, like if [[ 23ab = [0-9]{1,2}ab ]], it doesn't work right now.

Can you explain the difference between the two lines?

Upvotes: 3

Views: 444

Answers (1)

Charles Duffy
Charles Duffy

Reputation: 295619

[[ $a =~ $b ]] is a regular expression match. In this syntax, * matches 0-n instances of the immediately preceding character or pattern.

[[ $a = $b ]] is a glob-style pattern match. In this syntax, * matches 0-n characters of any type.

Note that it is important that regular expressions in bash be stored in variables. That is:

re='[0-9]{1,2}ab'
[[ $foo =~ $re ]]

may actually be different from

[[ $foo =~ [0-9]{1,2}ab ]]

...depending on which version of bash you're running. Always using a variable will prevent this from causing problems.

Note that these are both different from

re='[0-9]{1,2}ab'
[[ $foo =~ "$re" ]] ## <- LITERAL SUBSTRING MATCH _NOT_ REGULAR EXPRESSION MATCH

...in which case the quoting makes the contents of $re literal, ie. not treated like a regular expression in modern bash.

Upvotes: 5

Related Questions