检查 bash 中 if 语句中的两个条件

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/25404711/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-18 11:11:09  来源:igfitidea点击:

check two conditions in if statement in bash

bashif-statementconditional

提问by MLSC

I have problem in writing if statement

我在写 if 语句时遇到问题

var1=`COMMAND | grep <Something>`
if [ -n "$var1" ] && if [[ "$var1" != string ]]; then
    .
    .
    .
fi

I want to write if statement that check:

我想写 if 语句来检查:

If var1is not null ANDif string(could be helloword) is not in var1 then do stuff.

如果VAR1不为空是否串(可以是hello文字)是不是在VAR1然后做的东西。

How can I do that?

我怎样才能做到这一点?

回答by fedorqui 'SO stop harming'

Just use something like this:

只需使用这样的东西:

if [ -n "$var1" ] && [[ ! $var1 == *string* ]]; then
...
fi

See an example:

看一个例子:

$ v="hello"
$ if [ -n "$v" ] && [[ $v == *el* ]] ; then echo "yes"; fi
yes
$ if [ -n "$v" ] && [[ ! $v == *ba* ]] ; then echo "yes"; fi
yes

The second condition is a variation of what is indicated in String contains in bash.

第二个条件是String contains in bash 中指示的内容的变体。

回答by ooga

Other possibilities:

其他可能性:

if [ -n "$var1" -a "$var1" != string ]; then ...

if [ "${var1:-xxx}" != "string" ]; then ...

回答by opalenzuela

You should rephrase the condition like this:

你应该像这样改写条件:

var1=`COMMAND | grep <Something>`
if [ -n "$var1" ] && [[ "$var1" != "string" ]]; then
.
.
.
fi

or the equivalent:

或等价物:

if test -n "$var1"  && test "$var1" != "string"
then
...
fi