Using the && operator in an if statement

BashIf StatementSyntaxOperators

Bash Problem Overview


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?

Bash Solutions


Solution 1 - Bash

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 https://stackoverflow.com/q/2309849/1983854 and some references given there like What is the difference between test, [ and [[ ?.

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionZiyaddin SadigovView Question on Stackoverflow
Solution 1 - BashfedorquiView Answer on Stackoverflow