windowsbatch-file

If condition in batch files


@echo off
SET var1="Yes"
SET var2="No"
SET var3="Yes"
if %var1%=="Yes"
    echo Var1 set
if %var2%=="Yes"
    echo Var2 set
if %var3%=="Yes"
    echo Var3 set

If I run the above script I get the following error. Can anyone pls help?

The syntax of the command is incorrect.

Thanks.


Solution

  • The echo needs to either be at the end of the if statement:

    if %var1%=="Yes" echo Var1 set
    

    or of the following form:

    if %var1%=="Yes" (
        echo Var1 set
    )
    

    I tend to use the former for very simple conditionals and the latter for multi-command ones and primitive while statements:

    :while1
        if %var1%=="Yes" (
            :: Do something that potentially changes var1
            goto :while1
        )
    

    What your particular piece of code is doing is trying to execute the command if %var1%=="Yes" which is not valid in and of itself.