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

问题描述 投票:67回答:1

我有三个变量:

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

如何在if语句中使用和(&&)运算符如下:

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

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

bash if-statement syntax operators
1个回答
147
投票

所以为了使你的表达能够起作用,改变&&-a就可以了。

这是正确的:

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

或者喜欢

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

甚至

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

你可以在这个问题bash : Multiple Unary operators in if statementWhat is the difference between test, [ and [[ ?那里给出的一些参考资料中找到更多细节。

© www.soinside.com 2019 - 2024. All rights reserved.