代码之家  ›  专栏  ›  技术社区  ›  Debugger

Bash中运算符“=”和“==”之间有什么区别?

  •  57
  • Debugger  · 技术社区  · 15 年前

    = == ?

    2 回复  |  直到 15 年前
        1
  •  84
  •   Dennis Williamson    15 年前

    你必须使用 == (( ... )) :

    $ if (( 3 == 3 )); then echo "yes"; fi
    yes
    $ if (( 3 = 3 ));  then echo "yes"; fi
    bash: ((: 3 = 3 : attempted assignment to non-variable (error token is "= 3 ")
    

    您可以在中使用其中一个进行字符串比较 [[ ... ]] [ ... ] test

    $ if [[ 3 == 3 ]]; then echo "yes"; fi
    yes
    $ if [[ 3 = 3 ]]; then echo "yes"; fi
    yes
    $ if [ 3 == 3 ]; then echo "yes"; fi
    yes
    $ if [ 3 = 3 ]; then echo "yes"; fi
    yes
    $ if test 3 == 3; then echo "yes"; fi
    yes
    $ if test 3 = 3; then echo "yes"; fi
    yes
    

    “字符串比较?”,你说?

    $ if [[ 10 < 2 ]]; then echo "yes"; fi    # string comparison
    yes
    $ if (( 10 < 2 )); then echo "yes"; else echo "no"; fi    # numeric comparison
    no
    $ if [[ 10 -lt 2 ]]; then echo "yes"; else echo "no"; fi  # numeric comparison
    no
    
        2
  •  29
  •   Dominic Rodger    15 年前

    Bash reference :

    string1 == string2
    = 可以用来代替 ==