Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Bash regex =~ operator

Tags:

bash

shell

unix

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

like image 622
user339946 Avatar asked Oct 18 '13 04:10

user339946


People also ask

What is the =~ operator in bash?

A regular expression matching sign, the =~ operator, is used to identify regular expressions.

What does =~ mean in Shell?

it's the Equal Tilde operator that allows the use of regex in an if statement. 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)).

Can you use regex in bash?

Regex is a very powerful tool that is available at our disposal & the best thing about using regex is that they can be used in almost every computer language. So if you are Bash Scripting or creating a Python program, we can use regex or we can also write a single line search query.

What does [[ ]] mean in bash?

The [[ ... ]] part allows to test a condition using operators. Think of it as an if statement. In your example, you're using the -s operator, which tests that the referenced file is not empty.


1 Answers

  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.

like image 96
Carl Norum Avatar answered Oct 04 '22 11:10

Carl Norum