ZhangZhihui's Blog  
scnzzh@ZUBT:~$ re='^[0-9]+$'
scnzzh@ZUBT:~$ a=001
scnzzh@ZUBT:~$ b=a12
scnzzh@ZUBT:~$ if [ $a =~ $re ]; then echo 'yyy'; fi
bash: [: =~: binary operator expected
scnzzh@ZUBT:~$ if [[ $a =~ $re ]]; then echo 'yyy'; fi
yyy
scnzzh@ZUBT:~$ if [[ $b =~ $re ]]; then echo 'yyy'; else echo 'nnn'; fi
nnn

 

  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.

scnzzh@ZUBT:~$ if [[ 'a' =~ 'a' && 'a' == 'a' ]]; then echo 'yyy'; fi
yyy
scnzzh@ZUBT:~$ if [[ 'a' =~ 'a' && 'a' == 'b' ]]; then echo 'yyy'; fi
scnzzh@ZUBT:~$ if [[ 'a' =~ 'a' || 'a' == 'b' ]]; then echo 'yyy'; fi
yyy
scnzzh@ZUBT:~$

 

scnzzh@ZUBT:~$ re='^[0-9]+$'
scnzzh@ZUBT:~$ a=001
scnzzh@ZUBT:~$ if [[ $a =~ $re ]]; then echo 'yyy'; fi
yyy
scnzzh@ZUBT:~$ a='001'
scnzzh@ZUBT:~$ if [[ $a =~ $re ]]; then echo 'yyy'; fi
yyy
scnzzh@ZUBT:~$ if [[ '001' =~ '^[0-9]+$' ]]; then echo 'yyy'; fi
scnzzh@ZUBT:~$ if [[ '001' =~ $re ]]; then echo 'yyy'; fi
yyy
scnzzh@ZUBT:~$ if [[ $a =~ '^[0-9]+$' ]]; then echo 'yyy'; fi
scnzzh@ZUBT:~$

 

zzh@ZZHPC:~$ program=godoc
zzh@ZZHPC:~$ if [[ "$program" = "go"* ]]; then echo yyy; fi
yyy
zzh@ZZHPC:~$ if [[ "$program" == "go"* ]]; then echo yyy; fi
yyy
zzh@ZZHPC:~$ if [[ "$program" = "go" ]]; then echo yyy; else echo nnn; fi
nnn

 

[[ ]] 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.

posted on 2020-11-23 16:33  ZhangZhihuiAAA  阅读(1071)  评论(0编辑  收藏  举报