| by Arround The Web | No comments

Batch File Variables How to Set and Use Variables in Your Batch Scripts

Using batch files, a type of script task can be automated on a Windows machine. They are written in plain text that resembles the DOS command line. Data modification is possible with batch scripts and files by including variables. The user can store data they enter, such as text, numbers, or the outcomes of actions, can be stored in them. Throughout the batch script, developers can declare variables, assign them values, and use those values to do calculations. Using variables, batch script flow can be controlled.

Syntax to Declare a Variable

The variable is declared in a batch script using the set command and the variable’s name. Since they are not case-sensitive, variable names frequently incorporate numbers, characters, and underscores. It states the following:

SET VARIABLE_NAME=VALUE

As an illustration, the command that follows sets the variable name to the value “James”:

SET personName=James

Accessing Variable Values

The “%VARIABLE_NAME%” syntax can be used to use a variable. For instance, the following command shows the variable name’s value:

echo %personName%

This will output the text “James” to the console.

Scope of Variables

Batch files may include two different types of variables:

  • Local variables are only available within the batch file in which they are identified.
  • Global variables are accessible from any batch file that is running.

By default, in a batch file, all variables are global. To create a local variable, use the setlocal command. Using a local variable in a batch file is demonstrated here:

@echo off

setlocal

rem Set the local variable `countLocal` to 5.

set countLocal=10

echo Local Count Variable Value: %countLocal%

endlocal

REM This will not work; countLocal is out of scope

echo The Value of Local Variable is out of scope: %countLocal%

This batch file will display the following in the console. Only the block of code that begins with the setlocal command and concludes with the endlocal command has access to the variable countLocal.

User Input:

A developer can use a batch file variable to capture user input. Using the set /p command, you can request input from the user and then allocate the value corresponding to that input to a variable.

It reads as follows:

set /p VARIABLE_NAME=PROMPT_MESSAGE

For instance, the command below asks the user for their name and sets the input’s value to the variable user_Name:

set /p user_Name=What is your name?

The PROMPT_MESSAGE string can be used to display any text that we want the user to view. The variable VARIABLE_NAME will be used to hold the user input. The batch file shown here includes a variable to take user input:

@echo off

rem Prompt the user for their name.

set /p user_Name=What is your name?

rem Display the user's name.

echo My name is %user_Name%.

When the user runs the batch file using the command prompt, the batch script will prompt the user to enter the name and then print the name to the console.

Arithmetic Operations

Variables can be employed in batch scripting to carry out mathematical operations like addition, multiplication, etc. The set /a command can be used to give the outcome of an algebraic expression and store it to a variable. It reads as follows:

set /a VARIABLE_NAME=EXPRESSION

The command given below is used to set the variable sumResult after adding the values of the variable’s number1 and number2:

set /a sumResult= number1+ number2

Here is the list of basic Math functions:

  1. Multiplication (+)
  2. Subtraction (-)
  3. Divison (/)
  4. Multipliation (*)
  5. Modulus (%)
  6. Exponentiation (^)

The batch file is a tool that utilizes variables to perform arithmetic operations.

@echo off

set number1=10

set number2=20

::Calculate Sum

set /a sum_Result=number1+number2

set /a subtraction_Result=number2-number1

set /a multiplication_Result=number1*number2

set /a division_Result=number1/number2

set /a mod_Result=number1%%number2

echo The SUM/ADDITION of numbers is %sum_Result%.

echo The Subtraction of numbers is %subtraction_Result%.

echo The PRODUCT/MULTIPLICATION of numbers is %multiplication_Result%.

echo The DIVISION/QUOTIENT of numbers is %division_Result%.

echo The MODULUS of numbers is %mod_Result%.

Check out the output in the below attached image.

Conditional Statements

We can use variables in conditional statements in batch files. The flow of a batch file can be controlled by conditional statements, depending on specific circumstances. The most common conditional statement in batch files is the if statement.

The syntax is as follows:

if [condition] [command]

A Boolean expression that can only be evaluated as true or false constitutes the condition. Whenever the condition is true, the command is executed. The command is skipped if the criterion is false. For example:

The below batch file will prompt the user for their age and then check if they are old enough to vote. If the user is old enough to cast a vote, the echo command will be carried out. The echo command will be skipped if the user is not old enough to vote.

@echo off

rem Prompt the user for their age.

set /p voter_Age=Enter your age?

rem Check if the user is old enough to vote.

if %voter_Age% geq 18 (

echo You are old enough to vote.

) else (

echo You are not old enough to vote.

Output:

String Manipulation

Developers can manipulate strings using batch file variables. Changes to a string’s content are made through the process of string manipulation. Using several commands like set, echo, for, and if batch scripts can also alter strings. Here are a few instances of string modification utilizing batch files’ variables:

Concatenating Strings

Two strings can be joined together with the + operator. For instance, the command below joins the strings “Tony” and “James”:

@echo off

set myFirstName=Tony

set myLastName=James

rem Concatenate the first name and last name.

set stringConcatenate=%myFirstName% %myLastName%

echo Concatenation Result is: %stringConcatenate%

View the results of the aforementioned script.

Extracting Substrings

By employing the “: ” operator, a substring can be extracted from a string. The substring’s start position and end location are the two inputs for the “:” operator. At the beginning of the string, both the start and finish positions are calculated. In this case, the following command takes the string “Hello world” and removes the first 4 characters:

@echo off

setlocal enabledelayedexpansion

rem Input string

set inputString=Hello world

rem Extract the first 4 characters

set subString=!inputString:~0,4!

echo Extracted Sub-String: %subString%

endlocal

View the results of the aforementioned script.

Replacing Substrings

The rem operator can be used to replace a substring within a string. The substring that has to be replaced and the replacement substring are the two inputs for the rem operator. For instance, the word “James” in the string “My Old Name was James” is changed to the word “Tony” with the following command. Additionally, it modifies a few other terms:

@echo off

setlocal enabledelayedexpansion

rem Input string

set inputString=My Old Name was James

echo %inputString%

rem Replace "James" with "Tony"

set replaceResult=!inputString:James=Tony!

rem Replace "Old" with "New"

set replaceResult=!inputString:Old=New!

rem Replace "was" with "is"

set replaceResult=!inputString:was=is!

echo %replaceResult%

endlocal

View the results of the aforementioned script.

Splitting Strings

The user can divide a string into a collection of substrings using the for command. The variable that will hold the list of substrings and the delimiter that will be used to divide the string are the two inputs that the command requires. Using the space character as the delimiter, the following command, for instance, splits the string “Mission Impossible Rouge Nation” into a list of substrings:

@echo off

setlocal enabledelayedexpansion

rem Input string

set movieName=Mission Impossible Rouge Nation

rem Split the string into substrings

for %%a in (!movieName!) do (

echo Movie Title Split: %%a

)

endlocal

View the results of the aforementioned script.

Special Variables

There are a few special variables in batch files that have predefined values. A few examples of these variables are:

  • %DATE%: This variable contains the current date in the format “MM/DD/YYYY”.
  • %TIME%: This variable contains the current time in the format “HH:MM:SS”.
  • %RANDOM%: This variable contains a random number between 0 and 32767.

Code Snippet:

@echo off

echo Current Date: %DATE%

echo Current Time: %TIME%

echo Random Number: %RANDOM%

View the results of the aforementioned script.

Environment Variables

Batch scripts can also access system environment variables such as PATH, USERNAME, and COMPUTERNAME. To access these variables, use % symbols, as follows:

@echo off

echo My username is %USERNAME%

echo My Computer Name is %COMPUTERNAME%

echo Operating System is %OS%

echo JAVA Path is %JAVA_HOME%

View the results of the aforementioned script.

Conclusion

Batch file variables store values like text, numbers, or command output. They can be either local and global, with accesss limited to the code block. Commands like set, echo, and if are used to set, display, and control variable values, while if statements control file flow.

Share Button

Source: linuxhint.com

Leave a Reply