What is the difference between operator “=” and “==” in Bash?

后端 未结 2 793
渐次进展
渐次进展 2020-11-29 00:16

It seems that these two operators are pretty much the same - is there a difference? When should I use = and when ==?

2条回答
  •  半阙折子戏
    2020-11-29 00:55

    You must use == in numeric comparisons in (( ... )):

    $ 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 ")
    

    You may use either for string comparisons in [[ ... ]] or [ ... ] or 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
    

    "String comparisons?", you say?

    $ 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
    

提交回复
热议问题