Command Prompt for Windows




IF Examples

Example 1:

Consider the following batch file :-

:loop
GETKEY Option:
IF "%GETKEY%"="" { 
	GOTO loop
} ELSE IF "%GETKEY%"="A" {
	ECHO Option A selected
} ELSE IF "%GETKEY%"="B" {
	ECHO Option B selected
} ELSE {
	ECHO Unknown option!
	GOTO loop
}

This batch file displays the "Option:" prompt and waits for the user to either press the A or B key. It will continue to prompt the user, until either the A or B key is pressed.

Example 2:

Consider the following batch file :-

SET VAR=1
IF ( VAR == 1 ) {
	SET VAR=2
	ECHO %VAR%
}
ECHO %VAR%

This program displays 2 on the first line and 2 on the second line, because the IF command uses braces (ie. '{' and '}') instead of brackets (ie. '(' and ')'). See Command Grouping for more information on using braces instead of brackets to group commands.

Example 3:

Consider the following erroneous batch file :-

SET VAR=0
IF ( VAR != 0 ) {
:loop
	ECHO %VAR%
} ELSE {
	GOTO loop
}

This program will result in a No such label error, since jumping into an IF statement is not permitted, however, jumping out of an IF statement is permitted.