bash - ERROR: binary operator expected


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

 

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

 

  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:~$ if [[ '001' =~ '^[0-9]+$' ]]; then echo 'yyy'; fi
scnzzh@ZUBT:~$ 

 

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


免责声明!

本站转载的文章为个人学习借鉴使用,本站对版权不负任何法律责任。如果侵犯了您的隐私权益,请联系本站邮箱yoyou2525@163.com删除。



 
粤ICP备18138465号  © 2018-2025 CODEPRJ.COM