Batch Script Decision Making

Decision making in Batch Script can be accomplished using 'if' statements, which allow for decisions to be made between two or more options.

In its most basic form an ‘if’ statement executes a group of statements if an expression evaluates to true. Its basic syntax is as follows.

if expression (
    :: Statement(s) will execute if the expression is true.
)

The following example checks whether the values of two variables are the same and displays a message if they are.

set /A num1 = 10
set /A num2 = 10

if %num1% equ %num2% (
    echo num1 is equal to num2
)

This can be extended to execute a statement or statements if the expression is false as follows.

if expression (
    :: Statement(s) will execute if the expression is true.
) else (
    :: Statement(s) will execute if the expression is false.
)

This example adds an ‘else’ statement to the one above to output a message if ‘num1' and ‘num2’ are not equal.

set /A num1 = 10
set /A num2 = 10

if %num1% equ %num2% (
    echo num1 is equal to num2
) else (
    echo num1 is not equal to num2
)

‘if’ statements can also be nested one inside another.

set /A num1 = 10
set /A num2 = 10
set /A num3 = 20

if %num1% equ %num2% (
    if %num1% lss %num3% (
        echo num1 is equal to num2 and less than num3
    )
) else (
    echo num1 is not equal to num2 and less than num3
)