102

I have three variables:

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

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

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

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

codeforester
  • 39,467
  • 16
  • 112
  • 140
Ziyaddin Sadigov
  • 8,893
  • 13
  • 34
  • 41

1 Answers1

204

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 [[ ?.

Community
  • 1
  • 1
fedorqui
  • 275,237
  • 103
  • 548
  • 598
  • 18
    Note that [POSIX](http://pubs.opengroup.org/onlinepubs/000095399/utilities/test.html#tag_04_140_16) recommends the use of `&&` and `||` with the single bracket notation over `-a` and `-o`, so if you are writing portable code go for the first notation, otherwise the second and skip the third, especially since it can get awkward and hard to read if you need to group expressions. – Adrian Frühwirth May 06 '13 at 12:22