Piyush
Piyush

Reputation: 41

Clear variables values in batch

I am reading two text files to set the values of two variables (u,l). Now I want to write script to run multiple files. When it is reading first file it will set the variables from the respective files but when it is reading second file it will set the same values of those variables.

@echo on
set /p u=< ul.txt
set /p l=< ll.txt
echo %u%-%l%

I tried SETLOCAL/ENDLOCAL option but in that case it is not reading variables values and getting error that ECHO is off. Even I wrote set u= and set l= at the initial of the script but not working in my case.

Upvotes: 0

Views: 4956

Answers (1)

Dennis van Gils
Dennis van Gils

Reputation: 3452

Your code, as given, works fine. However, I'm guessing it is code from inside an if statement, or for loop. If that is the case, you should use delayed expansion. You can use delayded expansion like this:

This is an example, not the exact code you need:

@echo on
setlocal EnableDelayedExpansion

if 1 equ 1 (
set /p "u=< ul.txt"
set /p "l=< ll.txt"
echo !u!-!l!
)
pause

FOR /L %%G IN (1,1,1) DO (
set /p "u=< ul.txt"
set /p "l=< ll.txt"
echo !u!-!l!
)
pause

set /p u=< ul.txt
set /p l=< ll.txt
echo %u%-%l%
pause

Note that inside the if statement and for loop, you replace % signs, when they are around variable names, with !. So %someVar% becomes !someVar!, but %%F stays %%F.

Outside of if statements and for loops, so outside of (), you use the normal %someVar%

Upvotes: 1

Related Questions