【问题标题】:What is the difference between operator "=" and "==" in Bash?Bash 中的运算符“=”和“==”有什么区别?
【发布时间】:2010-04-08 13:40:42
【问题描述】:

这两个运算符似乎几乎相同 - 有区别吗?我应该什么时候使用=,什么时候使用==

【问题讨论】:

    标签: bash operators


    【解决方案1】:

    您必须在(( ... )) 的数字比较中使用==

    $ 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
    

    【讨论】:

    • 您不应该将==[test 一起使用。 == 不是 POSIX 规范的一部分,并且不适用于所有 shell(尤其是 dash,无法识别它)。
    • @chepner:没错,但问题是关于 Bash。
    【解决方案2】:

    在 POSIX 方面存在细微差别。摘自Bash reference

    string1 == string2
    如果字符串相等,则为真。 = 可以用来代替 == 以严格遵守 POSIX。

    【讨论】:

    • 虽然 bash 没有区别?只是便携性问题?
    猜你喜欢
    • 1970-01-01
    • 2022-06-10
    • 2023-03-15
    • 1970-01-01
    • 2018-08-16
    • 2012-10-10
    • 2010-12-25
    • 2010-11-15
    相关资源
    最近更新 更多