The way you did it is already correct to use the variable in a batch script. The command set
is used to assign a value to a variable and the command set /p
allows Voce to specify a text that will be presented to the user and the variable value will be a user input.
You could also use the command set /a
to specify a numerical expression, as in set /a soma=4+3
.
And then you use the variable along the script by placing its name between percentage signals: %<nome da variáve>%
.
But you can use the command echo
to control what will be displayed as a result of your batch script. The command @echo off
does not display each executed command, and when you use the echo
directly with some text, this text is displayed at the command prompt.
See your slightly modified batch script test:
[Test bat.]
@echo off
set /p nome=Informe o nome ou IP do destino:
echo O nome escolhido foi '%nome%'.
ping.exe %nome%
The result would be:
c:\>teste
Informe o nome ou IP do destino: pt.stackoverflow.com
O nome escolhido foi 'pt.stackoverflow.com'.
Pinging pt.stackoverflow.com [151.101.65.69] with 32 bytes of data:
Reply from 151.101.65.69: bytes=32 time=5ms TTL=61
Reply from 151.101.65.69: bytes=32 time=6ms TTL=61
Reply from 151.101.65.69: bytes=32 time=5ms TTL=61
Reply from 151.101.65.69: bytes=32 time=6ms TTL=61
Ping statistics for 151.101.65.69:
Packets: Sent = 4, Received = 4, Lost = 0 (0% loss),
Approximate round trip times in milli-seconds:
Minimum = 5ms, Maximum = 6ms, Average = 5ms
Editing
The colleague bfavaretto warned that perhaps the doubt was in relation to passing parameters to the file. BAT, and that the parameters can be recovered in the script using the variables %1
, %2
, etc., until %9
. The number in the variable will refer to the order of the parameter in the command line.
For example, the following batch script:
@echo off
echo %1
echo %2
It could be called that, and that would be the result:
C:\teste.bat parâmetro1 /parâmetro2
parâmetro1
/parâmetro2
Issue 2
Making the first batch with the concept of parameters would look like this:
[Test bat.]
@echo off
echo O nome ou IP do destino escolhido foi '%1'.
ping.exe %1
And it could be called that, and that would be the result:
C:\teste.bat pt.stackoverflow.com
O nome ou IP do destino escolhido foi 'pt.stackoverflow.com'.
Pinging pt.stackoverflow.com [151.101.193.69] with 32 bytes of data:
Reply from 151.101.193.69: bytes=32 time=6ms TTL=59
[...]
Welcome to Stackoverflow Caique. Avoid placing images with the code, always prefer to write the code directly in the question.
– Pedro Gaspar
What you want is to pass a parameter to the script, not declare a variable, right? Use
%1
for the first command line argument,%2
for the second and so on until%9
.– bfavaretto