检查 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
check two conditions in if statement in bash
提问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 hello
word) 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