Types of Variables
There are two types of variables in batch files. One is for parameters that can be passed when the batch file is called, and the other is done through the set command.
Command Line Arguments
Batch scripts support the concept of command-line arguments, in which arguments can be passed to the batch file when it is invoked.
The arguments can be called from the batch files through the variables %1, %2, %3, and so on.
For example, the batch script below accepts 3 command line arguments and echo's them to the command line screen:
@echo off
echo %1
echo %2
echo %3If the above batch script is stored in a file called parameter-test.bat and we were to run the batch as:
C:\my\path>parameter-test.bat 1 2 3And the above command produces the following output:
1
2
3set Command
The other way to initialize variables is the set command. The syntax of the set command is as follows.
set /A variable_name=valuewhere:
variable_nameis the name of the variable you want to set.valueis the value which needs to be set against the variable./Ais used if the value needs to be numeric.
For example, in this script a variable called message is defined and set with the value of "Hello World".
@echo off
set message=Hello World
echo %message%And the above command produces the following output:
Hello WorldNumeric Variables
It is possible to define a variable to hold a numeric value. This can be done by using the /A switch (also known as flag).
For example:
@echo off
SET /A a = 5
SET /A b = 10
SET /A c = %a% + %b%
echo %c%where:
- we assign the values 5 and 10 to two variables
aandbrespectively. - we sum these values and store the result in the variable
c. - Finally, we display the value of the variable
c.
The output of the above script is 15.
Arithmetic Operators
All the arithmetic operators work in batch files.
For example:
@echo off
SET /A a = 5
SET /A b = 10
SET /A c = %a% + %b%
echo %c%
SET /A c = %a% - %b%
echo %c%
SET /A c = %b% / %a%
echo %c%
SET /A c = %b% * %a%
echo %c%And the output is:
15
-5
2
50Local and Global Variables
In Batch Scripting there are variables with local and global scope.
By default, variables are global to your entire command prompt session.
Call the SETLOCAL command to make variables local to the scope of the script. After calling SETLOCAL, any variable assignment is cancelled when ENDLOCAL, EXIT or when execution reaches the end of file (EOF) in the script is called.
The difference between setting local and global variables is shown in the following script:
@echo off
set globalvar = 5
SETLOCAL
set var = 13145
set /A var = %var% + 5
echo %var%
echo %globalvar%
ENDLOCALEnvironment Variables
Environment Variables are preferable when there are variables that would be used across batch files.
The following example shows how to see the JAVA_HOME defined on a system.
@echo off
echo %JAVA_HOME%C:\mypath\JAVA5.0\jre