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

我有三个变量:

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

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

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

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

255591 次浏览

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

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 statement and some references given there like What is the difference between test, [ and [[ ?.