views:

202

answers:

3
@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.

+7  A: 

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.

paxdiablo
Thanks. Is it applicable only for echo or for all the commands which follow as a positive result for if statement?
bdhar
@bdhar, that's the syntax for the 'if' command so, yes, all of them, not just echo.
paxdiablo
+1 for a while loop in batch file.
Dave Webb
@paxdiablo, Thanks a lot.
bdhar
+2  A: 

Take a look on IF command help:

C:\Users\Rubens>if /?
Performs conditional processing in batch programs.

IF [NOT] ERRORLEVEL number command
IF [NOT] string1==string2 command
IF [NOT] EXIST filename command

So, you command must be in same IF line. Your script should be:

@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
Rubens Farias
+3  A: 

You can't put a newline like that in the middle of the IF. So you could do this:

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

Or, if you do want your statements spread over multiple lines you can use brackets:

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

However, when you're using brackets be careful, because variable expansion might not behave as you expect. For example:

set myvar=orange

if 1==1 (
   set myvar=apple
   echo %myvar%
)

Outputs:

orange

This is because everything between the brackets is treated as a single statement and all variables are expanded before any of the command between the brackets are run. You can work around this using delayed expansion:

setlocal enabledelayedexpansion
set myvar=orange

if 1==1 (
   set myvar=apple
   echo !myvar!
)
Dave Webb
Sage advice. ALL my cmd scripts begin with 'setlocal enableextensions enabledelayedexpansion' (and end with 'endlocal').
paxdiablo