Open In App

Basics of Batch Scripting

Batch Scripting consists of a series of commands to be executed by the command-line interpreter, stored in a plain text file. It is not commonly used as a programming language and so it is not commonly practiced and is not trending but its control and dominance in the Windows environment can never be neglected. Almost every task and every action can be performed and executed by a simple sequence of commands typed on the Windows Command Prompt. 

Batch Script execution

There are 2 ways to execute a batch script.



Typing commands again and again on the terminal can be a very tedious task to do if we have a very lengthy code. So option 2 is generally preferred to create batch files.

Creating Batch Files

Steps to create a Batch file are pretty simple:-



  1. Create a new text file with a ‘.txt‘ extension.
  2. Now rename this file with extension as ‘.bat‘ this creates a Batch file.
  3. Now open this .bat file in any text editor and start scripting.

To begin scripting we must be aware of the commands of the batch interface. The commands of Batch are sometimes similar to Linux Scripting commands.

Batch Commands

Basic batch commands are all case insensitive and can be used to perform a specific set of instructions:-

How to execute a batch command through cmd(command prompt)

Data Types in Batch

Note: Batch doesn’t support floating-point values i.e. values with precision.

Variables in Batch Scripting

A variable is an entity that stores a specific value and allows the user to perform any set of instructions on it. To create variables we use the command “SET” command. A variable, unlike many programming languages, can be assigned simply without specifying any data type to it.

SET my_variable=Hello World

To print this variable we need to use the command ECHO but with a slight variation. Since echo  prints both strings and variables to print string we simply write the string after ECHO as

ECHO Hello World

But to print a variable we use ECHO in a different way bypassing the variable names inside two percent signs (%)  so that variable name doesn’t become a string-

ECHO %my_variable%

Working with Batch Scripts

Creating our own Batch Scripts

Example 1: To print “GeeksForGeeks” on the command prompt with and without using a variable.

Without using a variable 

ECHO GeeksForGeeks

With a variable

SET my_var=GeeksForGeeks
ECHO %my_var%

Arithmetic Operators in a Batch Script

List of operators :

SET /A sum=1+1     ::addition operator
ECHO %sum%     
SET /A mul=7*9     ::multiplication operator
ECHO %mul%
SET /A div=9/3     ::Division operator
ECHO %div%
SET /A assign=10   ::Assignment operator
ECHO %assign%
SET /A assign+=15  ::Increment then assignment operator
ECHO %assign%
SET /A mod= 10%3   ::Modulus/Remainder operator
ECHO %mod%

Demonstration of all arithmetic operators 

Article Tags :