【问题标题】:Bash if statement with logical OR带有逻辑或的 Bash if 语句
【发布时间】:2014-06-25 21:57:50
【问题描述】:

我希望命令仅在字符串变量不等于与 foo 任何以 bar 开头的单词时执行。

if [[ $string != "foo" || $string != bar* ]]; then
commands
fi

当 $string=foo 和我使用以下代码时,它可以正常工作并且不执行任何命令:

if [[ $string != "foo" ]]; then
commands
fi

但是当我用 || 添加第二部分时命令在不应该执行的时候执行。

【问题讨论】:

  • 你需要 && 而不是 ||。想想吧。

标签: if-statement logical-operators


【解决方案1】:

你需要一个 and,而不是 or

 if [[ $string != "foo" && $string != bar* ]] ...

您的代码所说的是“字符串不等于 foo,或者字符串不以 bar 开头必须是真的” - 对于所有字符串都是如此。

你要说的是“字符串不等于foo一定是真的,并且字符串不是以bar开头的”。

(您也可以在 $string 周围加上双引号,如果有可能它可能是空的。)

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2019-08-15
    • 2016-01-30
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多