【问题标题】:What is the idea in this bash statement ( command || true )?这个 bash 语句(命令 || true )的想法是什么?
【发布时间】:2017-11-09 07:31:36
【问题描述】:

我在网上看到了下面的 bash 语句:

PYTHON_BIN_PATH=$(which python || which python3 || true)

我知道如果which python 失败,那么which python3 会被执行,但是我不明白条件末尾的true 的目的。有什么想法吗?

【问题讨论】:

    标签: bash


    【解决方案1】:

    尝试运行:(注意bla

    which python_bla || which python3_bla_bla || true
    echo $?
    0
    

    您将收到RC=0。这意味着它是成功进行下一个命令的构造。在这里我们知道python_blapython3_bla_bla 不存在,但仍然命令给rc=0 示例:检查以下三个命令的 RC,我已将 date 命令的拼写更改为不正确,但 true 导致 RC 仍为 0

    date;echo $?
    Thu Nov  9 01:40:44 CST 2017
    0
    datea;echo $?
    If 'datea' is not a typo you can use command-not-found to lookup the package that contains it, like this:
        cnf datea
    127
    datea||true;echo $?
    If 'datea' is not a typo you can use command-not-found to lookup the package that contains it, like this:
        cnf datea
    0
    

    注意:您也可以使用: 运算符代替true 以获得相同的结果。示例:

    command || :
    

    【讨论】:

      【解决方案2】:

      我猜要更严格一些。

      例如:

      如果aaa 不是现有的全局二进制文件。 执行which aaa后,可以执行echo $?,结果为1

      但如果你执行which aaa | true,结果将是0

      【讨论】:

        【解决方案3】:

        简单。它将检查您的系统是否具有开箱即用的 python(操作系统随附的 python 版本)或其中是否有 python 版本 3。它也会确认python的可执行路径,你可以简单地通过echo "$PYTHON_BIN_PATH"打印名为PYTHON_BIN_PATH的变量,也可以检查一次。

        编辑:这是一个易于理解的简单示例。假设我们有一个名为 val 且值为 NULL 的变量,我们这样做:

        echo $val || true
        

        输出将为 NULL,因为它的前一个命令没有给出任何输出。 假设我们有val=4,然后我们按如下方式运行它。

        val="4"
        echo $val || true
        4
        

        【讨论】:

        • 是的,但我询问了true
        • which python 不告诉你吗? python版本
        【解决方案4】:

        如果which 都失败,则将PYTHON_BIN_PATH 设置为空。

        明显没有区别

        PYTHON_BIN_PATH=$(which python || which python3 || true)
        

        PYTHON_BIN_PATH=$(which python || which python3)
        

        但是单独运行命令会使事情变得更加明显。假设系统上不存在python。

        $(which python || which python3)
        echo $? #Returning the exit status of the previous command
        1 # A non zero status generally means the previous statement failed
        $(which python || which python3 || true)
        echo $?
        0
        

        简而言之,在最后使用true 总是给出零退出状态

         $( command || true )
        

        【讨论】:

          猜你喜欢
          • 1970-01-01
          • 2016-02-15
          • 1970-01-01
          • 1970-01-01
          • 2018-11-19
          • 2016-10-15
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          相关资源
          最近更新 更多