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

Bash if语句在不同位置使用感叹号生成不同的结果

  •  0
  • Tai  · 技术社区  · 6 年前

    我的第一个问题是 为什么要放 ! 在if语句前面 出现语法错误时失败 status 不是双引号。我就是这么想的 [ ! $x = "string" ] 不同于 [ $x != "string" ] ?

    我的剧本如下。

    #!/bin/bash
    
    status=" "
    
    # Comparison 1: without error
    echo "-----Comparison 1-----"
    if [ ! $status = "success" ]
    then echo 'Error: status was not success but: ' $status
    else
      echo "The status is success."
    fi
    echo "-----Comparison 2-----"
    # Comparison 2: with error message but still shows success
    if [ $status != "success" ]
    then echo 'Error: status was not success but: ' $status
    else
      echo "The status is success."
    fi
    echo "-----Comparison 3-----"
    # Comparison 3: Correct result after quoting status
    if [ ! "$status" == "success" ]
    then echo 'Error: status was not success but: ' $status
    else
      echo "The status is success."
    fi
    echo "-----Comparison 4-----"
    # Comparison 4: Correct result after quoting status
    if [ "$status" != "success" ]
    then echo 'Error: status was not success but: ' $status
    else
      echo "The status is success."
    fi
    

    -----Comparison 1-----
    The status is success.
    -----Comparison 2-----
    ./test2.sh: line 14: [: !=: unary operator expected
    The status is success.
    -----Comparison 3-----
    Error: status was not success but:
    -----Comparison 4-----
    Error: status was not success but:
    

    其他问题

    • 为什么会产生 "The status is success." 在里面 Comparison 2 语法错误之后?if语句中的语法错误如何影响if语句的计算结果?

    p、 我知道我们需要 "" $status

    1 回复  |  直到 6 年前
        1
  •  2
  •   chepner    6 年前

    你需要引用 $status . 如果没有引号,你的第一个比较就是

    if [ ! = "success" ]
    

    ! success 不是相等的字符串。

    [

    if [ != "success" ]
    

    在条件2中看到的语法错误不是 语法错误,但 所引发的语法错误 [ 命令。命令本身运行正常,但退出状态为非零。