@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.
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.
[ == ] (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.
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.
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.")
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.
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! )
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With