bash 在 if 语句中使用 && 运算符

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/16396146/
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-09 23:40:27  来源:igfitidea点击:

Using the && operator in an if statement

bashif-statementsyntaxoperators

提问by Ziyaddin Sadigov

I have three variables:

我有三个变量:

VAR1="file1"
VAR2="file2"
VAR3="file3"

How to use and (&&) operator in if statement like this:

如何&&在 if 语句中使用 and ( ) 运算符,如下所示:

if [ -f $VAR1 && -f $VAR2 && -f $VAR3 ]
   then ...
fi

When I write this code it gives error. What is the right way?

当我编写此代码时,它会出错。什么是正确的方法?

回答by fedorqui 'SO stop harming'

So to make your expression work, changing &&for -awill do the trick.

因此,要使您的表达式起作用,更改&&for-a就可以了。

It is correct like this:

正确的是这样:

 if [ -f $VAR1 ] && [ -f $VAR2 ] && [ -f $VAR3 ]
 then  ....

or like

或喜欢

 if [[ -f $VAR1 && -f $VAR2 && -f $VAR3 ]]
 then  ....

or even

甚至

 if [ -f $VAR1 -a -f $VAR2 -a -f $VAR3 ]
 then  ....

You can find further details in this question bash : Multiple Unary operators in if statementand some references given there like What is the difference between test, [ and [[ ?.

您可以在这个问题bash 中找到更多详细信息:if 语句中的多个一元运算符以及那里给出的一些引用,例如测试、[ 和 [[ 之间什么区别?.