The way you did it is already correct to use the variable in a batch script. The set
command is used to assign a value to a variable and the set /p
command allows you to specify text that will be presented to the user and the value of the variable will be a user input.
You could also use the set /a
command to specify a numeric expression, such as set /a soma=4+3
.
And then you use the variable over the script by putting its name among percent signs: %<nome da variáve>%
.
But you can use the echo
command to control what will be displayed as a result of your batch script. The @echo off
command does not display each executed command, and when you use echo
directly with some text, that 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
Colleague bfavaretto warned against the fact that perhaps the doubt was in relation to passing parameters to the file. BAT, and that the parameters can be retrieved in the script using the variables %1
, %2
, etc., to %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 this, 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
[...]