batch file statement

Batch file if else statements

The batch script supports the conditional statements like if, if-else ..etc. In this article, I will discuss how you can use if and else in the batch file.

You can see this article, Batch file commands

Batch file if statement

The if the statement is one of the selection statements. It uses to select statements depending on the value of a controlling expression.

Syntax,

if ( controlling expression )
    statement

In the above scenario, the statement will only be executed if the controlling expression is non-zero.

c if else




Let see  an example,

The below script displays the message according to the argument enter by the user.

@ECHO OFF

IF "%1%"=="4" goto welcome
IF "%1%"=="6" goto Bye

echo invalid argument.
goto Exit

:welcome

echo Welcome to Aticleworld.
goto Exit

:Bye

echo Please visit Aticleworld again.
goto Exit

:Exit

When User Enter 4:

if batch

 

When User Enter 6:

if batch script

 

When User Enter anything except 4 and 6:

if batch script 2

 

Batch file if else statement

if else is a selection statement that used to select statements depending on the value of a controlling expression.

Syntax:

if (controlling expression )
statement1 
else
statement2

In the above scenario, statement1 will only be executed if the expression is non-zero. if the expression is zero, then statement2 will be executed.

Let see an example,

The below program check even numbers and odd numbers. If a number is divided by 2, it means it is an even number. If the number is not divided by 2, then it is an odd number.

@ECHO OFF

set /a num=%1%
SET /a mod=num %% 2
IF %mod% == 0 (

ECHO %num% is even 

)ELSE (

ECHO %num% is odd

)

 

How the above program works:

 

1 Case: When you entered even number:

We know that the modular division of an even number by 2 is 0. So expression (num%% 2) return 0, as we know expression ( 0 == 0) return 1. Now controlling expression of if statement is non-zero then body associated with if statement will execute.

if else

 

2 Case: When you entered an odd number:

For odd number expression (num %% 2) return 1, so expression ( 1== 0) return 0. Now controlling the expression of if statement is zero then body associated with if statement will skip.

if else batch

Recommended Articles for you: