What does the “=~” operator do in shell scripts?

后端 未结 4 1944
别那么骄傲
别那么骄傲 2020-12-29 06:48

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#

相关标签:
4条回答
  • 2020-12-29 07:11

    It matches regular expressions

    Refer to following example from http://tldp.org/LDP/abs/html/bashver3.html#REGEXMATCHREF

    #!/bin/bash
    
    input=$1
    
    
    if [[ "$input" =~ "[0-9][0-9][0-9]-[0-9][0-9]-[0-9][0-9][0-9][0-9]" ]]
    #                 ^ NOTE: Quoting not necessary, as of version 3.2 of Bash.
    # NNN-NN-NNNN (where each N is a digit).
    then
      echo "Social Security number."
      # Process SSN.
    else
      echo "Not a Social Security number!"
      # Or, ask for corrected input.
    fi
    
    0 讨论(0)
  • 2020-12-29 07:23

    Like Ruby, it matches where the RHS operand is a regular expression.

    0 讨论(0)
  • 2020-12-29 07:27

    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)

    0 讨论(0)
  • 2020-12-29 07:28

    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
    
    0 讨论(0)
提交回复
热议问题