Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What does the "=~" operator do in shell scripts?

Tags:

bash

shell

It seems that it is sort of comparison operator, but what exactly it does in e.g. the following code (taken from https://github.com/lvv/git-prompt/blob/master/git-prompt.sh#L154)?

    if [[ $LC_CTYPE =~ "UTF" && $TERM != "linux" ]];  then
            elipses_marker="…"
    else
            elipses_marker="..."
    fi

I'm currently trying to make git-prompt to work under MinGW, and the shell supplied with MinGW doesn't seem to support this operator:

conditional binary operator expected
syntax error near `=~'
`        if [[ $LC_CTYPE =~ "UTF" && $TERM != "linux" ]];  then'

In this specific case I can just replace the entire block with elipses_marker="…" (as I know my terminal supports unicode), but what exactly this =~ does?

like image 669
penartur Avatar asked Jun 26 '12 11:06

penartur


People also ask

What is && and || in shell script?

The operators "&&" and "||" shall have equal precedence and shall be evaluated with left associativity. For example, both of the following commands write solely bar to standard output: $ false && echo foo || echo bar $ true || echo foo && echo bar.

What is operator in bash script?

Bash has a large set of logical operators that can be used in conditional expressions. The most basic form of the if control structure tests for a condition and then executes a list of program statements if the condition is true. There are three types of operators: file, numeric, and non-numeric operators.

What is >& 2 in shell script?

and >&2 means send the output to STDERR, So it will print the message as an error on the console. You can understand more about shell redirecting from those references: https://www.gnu.org/savannah-checkouts/gnu/bash/manual/bash.html#Redirections.

What does $? Meaning in a bash script?

$? - It gives the value stored in the variable "?". Some similar special parameters in BASH are 1,2,*,# ( Normally seen in echo command as $1 ,$2 , $* , $# , etc., ) . Follow this answer to receive notifications.


2 Answers

It's a bash-only addition to the built-in [[ command, performing regexp matching. Since it doesn't have to be an exact match of the full string, the symbol is waved, to indicate an "inexact" match.

In this case, if $LC_CTYPE CONTAINS the string "UTF".

More portable version:

if test `echo $LC_CTYPE | grep -c UTF` -ne 0 -a "$TERM" != "linux"
then
  ...
else
  ...
fi
like image 141
MattBianco Avatar answered Sep 29 '22 13:09

MattBianco


It's a regular expression matching. I guess your bash version doesn't support that yet.

In this particular case, I'd suggest replacing it with simpler (and faster) pattern matching:

[[ $LC_CTYPE == *UTF* && $TERM != "linux" ]]

(note that * must not be quoted here)

like image 25
Michał Górny Avatar answered Sep 29 '22 12:09

Michał Górny