Clear variables values in batch - batch-file

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.

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%

Related

Set file names as variables in batch file

I have a question how to set multiple files as variables in batch file? I trying to do something with below script:
move c:\*.gpg q:\
for %%F in ("q:\*.gpg") do (set file=%%~nxF)
if exist q:\*.gpg echo done copying files: %file%
Above works fine only with one file. If there are more than two it only echos one of them. How can I echo in one line all the files that where copied?
There are multiple problems with your code
for %%F in ("q:\*.gpg") do (set file=%%~nxF)
if exist q:\*.gpg echo done copying files: %file%
First, you're assigning new values to the variable file each loop and then overwriting it every time without doing anything. Therefore after the loop file will only contain the value in the last loop. Move the echo part to inside the loop instead
Another problem is that variables are expanded at parse time by default. You need to enable delayed expansion and use ! instead of % to make it expand at runtime
Setlocal EnableDelayedExpansion
for %%F in ("q:\*.gpg") do (
set file=%%~nxF
echo done copying file: !file!
)
If you want to echo all files at once then set the file variable to contain the list of files
for %%F in ("q:\*.gpg") do (
set file=!file!, %%~nxF
)
echo done copying files: %file%
The file existence check is redundant. You can check the exit code after moving and exit if the files weren't moved.
The variables are not constant so remember to activate the expansion delayed variable, here the expansion of the variable file must be delayed.
Delayed Expansion will cause variables to be expanded at execution time rather than at parse time, this option is turned on with the SETLOCAL command. When delayed expansion is in effect variables can be referenced using !variable_name! (in addition to the normal %variable_name% )
Delayed variable expansion is often useful when working with FOR Loops, normally an entire FOR loop is evaluated as a single command even if it spans multiple lines of a batch script.
This is the default behaviour of a FOR loop:
Example :
#echo off
setlocal
:: count to 5 storing the results in a variable
set _tst=0
FOR /l %%G in (1,1,5) Do (echo [%_tst%] & set /a _tst+=1)
echo Total = %_tst%
C:\> demo_batch.cmd
[0]
[0]
[0]
[0]
[0]
Total = 5
Notice that when the FOR loop finishes we get the correct total, so the variable correctly increments, but during each iteration of the loop
the variable is stuck at it's initial value of 0
The same script with EnableDelayedExpansion, gives the same final result but also displays the intermediate values:
#echo off
setlocal EnableDelayedExpansion
:: count to 5 storing the results in a variable
set _tst=0
FOR /l %%G in (1,1,5) Do (echo [!_tst!] & set /a _tst+=1)
echo Total = %_tst%
C:\> demo_batch.cmd
[0]
[1]
[2]
[3]
[4]
Total = 5
Notice that within the for loop we use !variable! instead of %variable%.
And your batch script can be written like that :
#echo off
Set "Ext=*.gpg"
set /a Count=0
Setlocal EnableDelayedExpansion
for %%F in ("q:\%Ext%") do (
SET /a Count+=1
set "file=%%~nxF"
echo Done copying file [!Count!] : !file!
)
SET /a "COUNT_TOT=%Count%"
ECHO.
ECHO Total of [%EXT%] files(s) : %Count% file(s)
pause

Echo &variable% in a loop is delayed by 1 count. Echo is off error

Im trying to make a CMD batch script that will do the following.
Read the first line of a text file. The first line of the text file contains a date.
Delete the text file if the date is 3 months old from current date.
For illustration,
the first line of file A is Hello1, the first line of file B is Hello2
I want to get an output showing this
%counter% %first line of text file%,
so for my example it should look like this:
2 Hello2
1 Hello1
but instead, i am getting this:
2
1 Hello2
My current code is this.
set file.1=A.txt
set file.2=B.txt
set counter=2
SETLOCAL EnableDelayedExpansion
set counter=%counter%
:loop
if %counter% NEQ 0 (
set /p texte=<!file.%counter%!
echo %counter% %texte%
set /a counter=%counter%-1
gotop loop)
How do I fix this?
You have set it up for delayed expansion with your setlocal command (which should probably have a corresponding endlocal by the way) but you don't appear to be using delayed expansion in all the places it's needed.
Delayed expansion of variables requires the use of ! for expansion, not %.
Of course, once you do that, you're going to find issues with an expression like !file.!counter!! because cmd.exe is not the, err, greatest tool in the world :-)
However, that fact has produced some of the sneakiest coders in the world by forcing them to work around such limitations and you can do double-indirection of variables by using call as per the following program:
#setlocal enableextensions enabledelayedexpansion
#echo off
set file.1=A.txt
set file.2=B.txt
set counter=2
:loop
if !counter! NEQ 0 (
call :sneaky_set fspec file.!counter!
set /p texte=<!fspec!
echo !counter! !texte!
set /a counter=!counter!-1
goto loop
)
endlocal
goto :eof
:sneaky_set
set %1=!%2!
goto :eof
The call statement there passesfspec and file.N (the first level of indirection and where N is the current value in counter) to sneaky_set. It in turn executes:
set fspec=!file.N!
which is the second level of indirection and therefore sets file to the correct *.txt value.

set /A command expands with a comma for more than one var, only set does not

(set /a "m1=1,m2=2")
for /f %%c in ("%m1%%m2%") do echo %%c
pause
The brackets else where than due to the for command are used in cases, a space key should have been added.
The echo of the for command, is 12. I used the number characters to face the set /A command with decimal Expression.
When i try the same procedure only with a set for a Shell, may also be named m1 it is just possible without comma seperation.
With set command the m1 Expression would be 1 m2 2 and not two values like with a set /A SET.
Is there a way to use set only once and not only with the set /A?
As other answers and comments already indicated, there is no way to directly do this in one command, but via a procedure. The method below is the simplest one:
#echo off
rem Define the several values
set "vars=m1=1,m2=2"
rem Do it:
set "%vars:,=" & set "%"
echo m1=%m1%
echo m2=%m2%
You may remove the #echo off command and execute this program to see what exactly is executed...
As I understand the question you want something like:
set x=1,y=2
and as a result to have two variables (like set /a). The answer is no.
Though you can iterate trough expressions with plain for :
#echo off
for %%a in (
"x=1" "a=5"
"y=2" "b=6"
"z=3" "c=7"
) do set "%%~a"
echo %x% %y% %z% %a% %b% %c%
Mind that the quotes around the items are mandatory because = is a delimiter. You can put everything on line and to use as separators , ,; ,<space>
May be with a lot of variables this can save you from some writing...?
this can be rewritten like this:
#echo off
set "vars=x=1,y=2,z=3,a=5,b=6,c=7"
for %%a in ("%vars:,=","%") do set "%%~a"
echo %x% %y% %z% %a% %b% %c%
And thus you'll need to change only the vars value.

Batch file for loop dynamic variables from file without setlocal?

I have a simple ini file... really just a key=value file that I want to use to set as variables for my script.
My ini file:
DATABASE=snoopy
My Batch file code
#echo off
SET DATABASE=woodstock
FOR /f "tokens=1,2 delims==" %%a in ('C:\mycfg.ini') do (
echo a=%%a
echo b=%%b
pause
SET %%a=%%b
ECHO DATABASE=%DATABASE%
)
The echo a and b are correct, it shows
a=DATABASE
b=snoopy
But at the end when I echo %DATABASE% after calling the SET %%a=%%b
It still shows
DATABASE=woodstock
If I use delayed expansion, it works but only locally. I need it to overwrite the global so I don't see why this shouldn't work.
Well, no need to do anything to make it work.
It works.
Your problem is that when the for block (all the lines in parenthesis in your code) are read, variables are replaced with their values, so the line echo %DATABASE% is converted in echo woodstock. BUT the variable hold the correct value, changed inside the for loop. Try to place the echo outside of the for and see what the value is.
Delayed expansion is needed when a variable is changed inside a block and it is necesary to access the changed value inside the same block.
Ok I got it now..
Had to enable delayed expansion at the top of the file rather than just on the subroutine call. Then set the %%a and %%b to delayed variables and set them equal to eachother and that worked. Final code:
#echo off
SetLocal EnableDelayedExpansion
SET DATABASE=woodstock
FOR /f "tokens=1,2 delims==" %%a in ('C:\mycfg.ini') do (
set tmpA=%%a
set tmpB=%%b
SET !tmpA!=!tmpB!
)
ECHO DATABASE=%DATABASE%
And that changes it to "snoopy"
Thanks all!

Batch File - for /F loop - read multiple Variables

I need to load different numeric values from external config.txt file and write them to %variables% in batch file. Example - config.txt file should looks as following:
====================
Setting1=1
Setting2=0
Setting3=1
====================
I need to assign first value (1) lets say into variable %1%, second value (0) into variable %2% and so on.
Could you please help me how to do this?
Thanks.
try this:
#echo off&setlocal
for /f %%i in (config.txt) do set "%%i" 2>nul
set "setting"
Do you know how many variables there will be? If you don't then go with Endoro's answer. If you do know how many variables there will be and you want to set them to a custom name you could do this:
#echo off
< config.txt (
set /p var1=
set /p var2=
set /p var3=
)
echo %var1%
echo %var2%
echo %var3%
pause
You shouldn't use %1% or plain numbers for variables, it can mess it up.
If config.txt had those '=' signs then you would have to skip add two more lines for the var's.
The reason you should use this for custom variables is because you could name the variables by there specific meaning which may make it easier to remember when coding.
Ex.
#echo off
< config.txt (
set /p name=
set /p pizza=
set /p car=
)
echo %name%
echo %pizza%
echo %car%
pause

Resources