Reputation: 3
When I do this in Notepad, the command prompt doesn't show ping %ip% -t -l %package%
, but it shows ping %ip% -t -l
and doesn't show the package variable.
@echo off
set data=0
set package = -600
IF %data% == 0 (
set /a package= %package% + 1600
@echo ping %ip% -t -l %package%
)
echo %package%
pause
What am I doing wrong?
Upvotes: 0
Views: 124
Reputation: 79983
Batch is sensitive to spaces in a SET
statement. SET FLAG = N
sets a variable named "FLAGSpace" to a value of "SpaceN"
The set "var=value"
syntax ensures that any trailing spaces on the batch line are not included in the value assigned to var
.
Within a block statement (a parenthesised series of statements)
, the entire block is parsed and then executed. Any %var%
within the block will be replaced by that variable's value at the time the block is parsed - before the block is executed - the same thing applies to a FOR ... DO (block)
.
Hence, IF (something) else (somethingelse)
will be executed using the values of %variables%
at the time the IF
is encountered.
Two common ways to overcome this are 1) to use setlocal enabledelayedexpansion
and use !var!
in place of %var%
to access the changed value of var
or 2) to call a subroutine to perform further processing using the changed values.
Note therefore the use of CALL ECHO %%var%%
which displays the changed value of var
.
So:
@echo off
SETLOCAL ENABLEDELAYEDEXPANSION
set /A data=0
set /A package=-600
IF %data% == 0 (
set /a package=!package!+1600
echo ping %ip% -t -l !package!
)
echo %package%
pause
Noting: The setlocal
statement should normally be placed at the start of the code. Your posted code is evidently a snip, since you do not appear to be setting ip
.
Spaces are irrelevant in a set /a
but even so, removing them fosters a habit
Set /a
uses the run-time
value, not the parse-time
value of var
when the syntax set /a var=var+1
is used within a loop, so set /a var=var+1
and set /a var=!var!+1
are equivalent but set /a var=%var%+1
uses the value of var
at the time the loop is parsed
.
Since echoing is set to off
by the initial statement, the leading @
on the second echo
is redundant.
Upvotes: 1