【问题标题】:Is it possible to combine two Linux conditions?是否可以结合两个 Linux 条件?
【发布时间】:2017-02-16 15:00:14
【问题描述】:

在 Linux 中,您可以执行简单的命令行条件,例如。

echo 'The short brown fox' | grep -q 'fox' && echo 'Found' || echo 'Not Found'

>> Found

或者

test -e test.txt && echo 'File Exists' || echo 'File Not Found'
>> File exists

这两个条件可以合二为一吗?因此,如果找到 fox,我们会查看文件是否存在,然后相应地执行条件。

我尝试了以下方法,但它们似乎不起作用:

echo 'The short brown fox' | grep -q 'fox' && (test -e test.txt && echo 'File Exists' || echo 'File Not Found') || echo 'Fox Not Found'

echo 'The short brown fox' | grep -q 'fox' && `test -e test.txt && echo 'File Exists' || echo 'File Not Found'` || echo 'Fox Not Found'

我需要在一行中执行命令。

【问题讨论】:

    标签: csh


    【解决方案1】:

    您可以使用 { ...; } 在 shell 中对多个命令进行分组,如下所示:

    echo 'The short brown fox' | grep -q 'fox' &&
    { [[ -e test.txt ]] && echo "file exists" || echo 'File Not Found'; } || echo 'Not Found'
    

    grep 成功并且|| 外部{ ...; } 被评估为grep 失败时,将执行大括号内的所有命令,即{ ...; }


    编辑:

    这是csh 一个班轮做同样的事情:

    echo 'The short brown ox' | grep -q 'fox' && ( [ -e "test.txt" ] && echo "file exists" || echo 'File Not Found' ; ) || echo 'Not Found'
    

    【讨论】:

    • 这似乎只是错误:{:找不到命令。未找到文件}:未找到命令。未找到
    • 你用的是什么外壳?这对我来说在bash 中工作得很好
    • 我正在使用-csh
    【解决方案2】:

    不要像这样组合||&&;使用明确的if 语句。

    if echo 'The short brown fox' | grep -q 'fox'; then
        if test -e test.txt; then
            echo "File found"
        else
            echo "File not found"
        fi
    else
        echo "Not found"
    fi
    

    如果a 成功而b 失败,则a && b || c 不等价(尽管您可以使用a && { b || c; },但if 语句更具可读性)。

    【讨论】:

    • 这不能在单行上运行。
    • 当然可以; if ...; then if ...; then echo; else; echo; fi; else echo; fi。但是你想要一个简短的命令,还是一个正确的命令?几乎任何你在 shell 中看到换行符的地方,你都可以用分号替换它。
    • 刚注意到标签中csh的变化。不确定这个答案是否仍然适用,但有很多理由从 csh 切换到 bash(或至少与 POSIX 相关的东西)。
    【解决方案3】:

    是的!您可以像这样使用 and 和 or 运算符:

    echo "The short brown fox" | grep fox && echo found || echo not found
    

    如果您还想抑制grep 的输出,以便只看到“找到”或“未找到”,您可以这样做:

    echo "The short brown fox" | grep fox >/dev/null && echo found || echo not found
    

    && 运算符和 || 运算符是短路的,所以如果 echo "The short brown fox" | grep fox >/dev/null 返回一个真实的退出代码 (0),那么 echo found 将执行,因为这也返回一个退出代码 0, echo not found 永远不会执行。

    同样,如果echo "The short brown fox" | grep fox >/dev/null 返回错误的退出代码 (>0),则 echo found 将根本不执行,echo not found 将执行。

    【讨论】:

      猜你喜欢
      • 2021-11-03
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2017-06-07
      • 2020-02-15
      • 2013-02-08
      • 2019-10-28
      • 1970-01-01
      相关资源
      最近更新 更多