How to Use //P With the SET Command in Batch Script

MD Aminul Islam Feb 02, 2024
How to Use //P With the SET Command in Batch Script

SET is a variable used when we want to declare a variable and assign it with a value, but we sometimes use /P with this command. This article will show the purpose of using /P with the SET command.

Use /P With the SET Command in Batch Script

As we know, the general format for declaring variables in Batch Script is:

set VARIABLE_NAME=VALUE

In this way, we can directly declare a variable and assign it values.

Using /P, you will be able to assign a value to a variable from the user input. Then the general format of this command will look like the following:

SET /P VARIABLE_NAME=

Now, if you want to guide users about what kind of value they need to enter, you can add an instructional string on it such as:

set /P VARIABLE="INSTRUCTIONAL STRING"

Let’s see some examples to make it clear.

In this example, we will take a numeric value for the user as the age and show it as an output. We will include an instructional string Enter your age: to guide the user about what kind of input he needs to provide.

After that, we will take that user input and assign it to the variable age. Lastly, we will use the echo command to show the age as output.

Take a look at our example and its output.

@echo off
set /p age="Enter your age: "
echo Your age is: %age%
pause

Output:

Enter your age: 23
Your age is: 23

Now, we will discuss another example of using /P with the SET command.

This example will take two variables as input, sum them up, and show the result as output. Here we will use two SET command with /P that takes the input of two numbers from the user one by one.

Then we will use another SET command with /A that assigns a value in the variable c after summing the two variables taken from the user. Here /A means it is an arithmetic operation.

Lastly, we show the result as output. Let’s take a look at our example and the output.

@echo off
set /p a="Enter first number: "
set /p b="Enter second number: "
set /a c=%a%+%b%
echo Sum is: %c%
pause

The output of the program will look like the below.

Output:

Enter first number: 12
Enter second number: 12
Sum is: 24

Please note that the code we showed using this command is written in Batch and only for the Windows CMD environment.

MD Aminul Islam avatar MD Aminul Islam avatar

Aminul Is an Expert Technical Writer and Full-Stack Developer. He has hands-on working experience on numerous Developer Platforms and SAAS startups. He is highly skilled in numerous Programming languages and Frameworks. He can write professional technical articles like Reviews, Programming, Documentation, SOP, User manual, Whitepaper, etc.

LinkedIn

Related Article - Batch Command