Batch Script - Nested If Statements


Advertisements

Sometimes, there is a requirement to have multiple ‘if’ statement embedded inside each other. Following is the general form of this statement.

if(condition1) if (condition2) do_something

So only if condition1 and condition2 are met, will the code in the do_something block be executed.

Following is an example of how the nested if statements can be used.

Example

@echo off
SET /A a = 5
SET /A b = 10
if %a%==5 if %b%==10 echo "The value of the variables are correct"

Output

The above command produces the following output.

"The value of the variables are correct"

If errorlevel

Yet another special case is "if errorlevel", which is used to test the exit codes of the last command that was run. Various commands issue integer exit codes to denote the status of the command. Generally, commands pass 0 if the command was completed successfully and 1 if the command failed.

Following is the general syntax of this statement.

if errorlevel n somecommand

where "n" is one of the integer exit codes.

Goto Statement

Generally, the execution of a batch file proceeds line-by-line with the command(s) on each line being run in turn. However, it is often desirable to execute a particular section of a batch file while skipping over other parts. The capability to hop to a particular section is provided by the appropriately named "goto" command (written as one word). The target section is labeled with a line at the beginning that has a name with a leading colon. Thus the script looks like −

... 
goto :label 
...some commands 
:label 
...some other commands

Execution will skip over "some commands" and start with "some other commands". The label can be a line anywhere in the script, including before the "goto" command. "Goto" commands often occur in "if" statements. For example, you might have a command of the type −

if (condition) goto :label

Following is an example of how the goto statement can be used.

Example

@echo off 
SET /A a = 5 

if %a%==5 goto :labela 
if %a%==10 goto :labelb

:labela 
echo "The value of a is 5" 

exit /b 0

:labelb 
echo "The value of a is 10"

The key thing to note about the above program is −

  • The code statements for the label should be on the next line after the declaration of the label.

  • You can define multiple goto statements and their corresponding labels in a batch file.

  • The label declarations can be anywhere in the file.

Output

The above command produces the following output.

"The value of a is 5" 
batch_script_decision_making.htm
Advertisements