1

I have this issue where I want to re-define a variable with each iteration of a for loop. I cannot figure out why this is not working. I have tried messing with enabledelayedexpansion but have not had success.

echo off
for /f "tokens=1-7 delims=::/ " %%A in ("%DATE% %TIME%") do set capture_time=%%D-%%B-%%C_%%E%%F%%G
for /l %%a in (1,1,3) do (
    echo %capture_time%
    timeout 3 /nobreak
    for /f "tokens=1-7 delims=::/ " %%A in ("%DATE% %TIME%") do set capture_time=%%D-%%B-%%C_%%E%%F%%G
)

My desired output would be something like this:

2015-08-27_132506.50
2015-08-27_132509.50
2015-08-27_132512.50

Where each time the loop is run, the capture_time is updated.

CephBirk
  • 6,422
  • 5
  • 56
  • 74
  • 2
    You fell into the [delayed expansion](http://stackoverflow.com/a/10558905/5047996) trap! The variable _is_ set but it is expanded earlier so you don't see the updated value... In [this code](http://stackoverflow.com/q/30234238/5047996) for instance, there is exactly the same problem... – aschipfl Aug 27 '15 at 21:54
  • I applied the answer from your first link but it still didn't work. Is it different because I am re-defining the variable "from scratch" each iteration? – CephBirk Aug 27 '15 at 22:13
  • 1
    The delayed expansion must also be applied to `!DATE!` and `!TIME!`... – aschipfl Aug 27 '15 at 22:15
  • Would you like to make this an official answer? – CephBirk Aug 28 '15 at 02:34
  • See @Mofi's [answer](http://stackoverflow.com/a/32264304/5047996)... – aschipfl Aug 28 '15 at 12:32

1 Answers1

1

Every environment variable within a block defined with ( and ) and referenced with %Variable Name% is expanded already by command processor on parsing the block. This can be seen on running a batch file from within a command prompt window with using echo on or having @echo off removed or commented out with rem.

The solution is using delayed expansion as demonstrated below.

@echo off
setlocal EnableDelayedExpansion
for /f "tokens=1-7 delims=::/ " %%A in ("%DATE% %TIME%") do set "capture_time=%%D-%%B-%%C_%%E%%F%%G"
for /l %%a in (1,1,3) do (
    echo !capture_time!
    timeout 3 /nobreak
    for /f "tokens=1-7 delims=::/ " %%A in ("!DATE! !TIME!") do set "capture_time=%%D-%%B-%%C_%%E%%F%%G"
)
endlocal

For more details on delayed expansion open a command prompt window, execute there set /? and read all help pages output into the command prompt window carefully. Delayed expansion is explained in help on an example.

Why it is always better to use set "variable=value" instead of set variable=value is explained for example here.

Community
  • 1
  • 1
Mofi
  • 46,139
  • 17
  • 80
  • 143