用逻辑OR打击if语句

use*_*083 2 if-statement logical-operators

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

if [[ $string != "foo" || $string != bar* ]]; then
commands
fi
Run Code Online (Sandbox Code Playgroud)

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

if [[ $string != "foo" ]]; then
commands
fi
Run Code Online (Sandbox Code Playgroud)

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

Ric*_*dle 6

您需要and,而不是or

 if [[ $string != "foo" && $string != bar* ]] ...
Run Code Online (Sandbox Code Playgroud)

您的代码在说的是“字符串不等于foo或字符串不以bar开头必须为真”-所有字符串都是正确的。

您需要说的是“字符串不等于foo一定是正确的,并且字符串不能以bar开头 ”。

$string如果有可能它可能为空,您可能还希望在双引号中加上双引号。)