Bash regex =~ operator

BashShellUnix

Bash Problem Overview


What is the operator =~ called? Is it only used to compare the right side against the left side?

Why are double square brackets required when running a test?

ie. [[ $phrase =~ $keyword ]]

Thank you

Bash Solutions


Solution 1 - Bash

  1. > What is the operator =~ called?

    I'm not sure it has a name. The bash documentation just calls it the =~ operator.

  2. > Is it only used to compare the right side against the left side?

    The right side is considered an extended regular expression. If the left side matches, the operator returns 0, and 1 otherwise.

  3. > Why are double square brackets required when running a test?

    Because =~ is an operator of the [[ expression ]] compound command.

Solution 2 - Bash

The =~ operator is a regular expression match operator. This operator is inspired by Perl's use of the same operator for regular expression matching.

The [[ ]] is treated specially by bash; consider that an augmented version of [ ] construct:

  • [ ] is actually a shell built-in command, which, can actually be implemented as an external command. Look at your /usr/bin, there is most likely a program called "[" there! Strictly speaking, [ ] is not part of bash syntax.

  • [[ ]] is a shell keyword, which means it is part of shell syntax. Inside this construct, some reserved characters change meaning. For example, ( ) means parenthesis like other programming language (not launching a subshell to execute what's inside the parentheses). Another example is that < and > means less than and greater than, not shell redirection. This allow more "natural" appearance of logical expressions, but it can be confusing for novice bash programmers.

Wirawan

Solution 3 - Bash

The =~operator is the pattern match operator. It did not exist in the original Bourne shell, when test, or internally [ ], was used for conditionals.

The let command, or [[ ]] internally, has more functionality than test, including pattern matching capabilities. This is why you have to use [[ ]], instead of [ ], when using =~.

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
Questionuser339946View Question on Stackoverflow
Solution 1 - BashCarl NorumView Answer on Stackoverflow
Solution 2 - BashWirawan PurwantoView Answer on Stackoverflow
Solution 3 - BashAnthony RutledgeView Answer on Stackoverflow