Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

If condition in batch files

Tags:

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

like image 816
bdhar Avatar asked Dec 23 '09 09:12

bdhar


People also ask

Can you use if statements in batch files?

One of the common uses for the 'if' statement in Batch Script is for checking variables which are set in Batch Script itself. The evaluation of the 'if' statement can be done for both strings and numbers.

What is == in batch file?

[ == ] (Double Equals) The "IF" command uses this to test if two strings are equal: IF "%1" == "" GOTO HELP. means that if the first parameter on the command line after the batch file name is equal to nothing, that is, if a first parameter is not given, the batch file is to go to the HELP label.

Is it possible to apply if function in CMD?

If the condition specified in an if clause is true, the command that follows the condition is carried out. If the condition is false, the command in the if clause is ignored and the command executes any command that is specified in the else clause. When a program stops, it returns an exit code.

Does batch have else if?

However, you can't use else if in batch scripting. Instead, simply add a series of if statements: if %x%==5 if %y%==5 (echo "Both x and y equal 5.")


2 Answers

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.

like image 134
paxdiablo Avatar answered Oct 12 '22 13:10

paxdiablo


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! ) 
like image 33
Dave Webb Avatar answered Oct 12 '22 12:10

Dave Webb