Batch Script Decision Making If Statement - Batch Script

How does if statement work in decision making

Syntax

The general working of this statement is that first a condition is evaluated in the ‘if’ statement. If true, it then executes the statements. Here is how it works:

if statement

How to check Variables

‘If’ statement in Batch Script is used to check variables which are set in Batch Script itself. The evaluation of the ‘if’ statement can be done for both strings and numbers.

Checking Integer Variables

Example
Note
  • The first ‘if’ statement checks if the value of the variable c is 15. If so, then it echo’s a string to the command prompt.
  • Since the condition in the statement - if %c% == 10 echo "The value of variable c is 10 evaluates to false, the echo part of the statement will not be executed.
Output

Checking String Variables

Example
Note
  • The first ‘if’ statement checks if the value of the variable str1 contains the string “String1”. If so, then it echo’s a string to the command prompt.
  • Since the condition of the second ‘if’ statement evaluates to false, the echo part of the statement will not be executed.
Output
Note − One key thing to note is that the evaluation in the ‘if’ statement is "case-sensitive”. The same program as above is modified a little as shown in the following example. In the first statement, we have changed the comparison criteria. Because of the different casing, the output of the following program would yield nothing.

Checking Command Line Arguments

‘If’ statement is also used to check for the values of the command line arguments which are passed to the batch files.
Example
Note
  • The above program assumes that 3 command line arguments will be passed when the batch script is executed.
  • A comparison is done for each command line argument against a value. If the criteria passes then a string is sent as the output.

Output

If the above code is saved in a file called test.bat and the program is executed as
Following will be the output of the above program.

All rights reserved © 2018 Wisdom IT Services India Pvt. Ltd DMCA.com Protection Status

Batch Script Topics