Update variable in a For loop

Discussion forum for all Windows batch related topics.

Moderator: DosItHelp

Post Reply
Message
Author
darioit
Posts: 230
Joined: 02 Aug 2010 05:25

Update variable in a For loop

#1 Post by darioit » 14 Oct 2015 01:45

Hello folks,

why in a FOR loop, %time% variable doesn't update?

Code: Select all

@echo off
for /f "delims=" %%a in ('dir /b *.*') do (
   echo %time%
   )


Result:
9:44:07.81
9:44:07.81
9:44:07.81
9:44:07.81
9:44:07.81
9:44:07.81
9:44:07.81

Thank you

ShadowThief
Expert
Posts: 1166
Joined: 06 Sep 2013 21:28
Location: Virginia, United States

Re: Update variable in a For loop

#2 Post by ShadowThief » 14 Oct 2015 01:49

You need delayed expansion.

Code: Select all

@echo off
setlocal enabledelayedexpansion
for /f "delims=" %%a in ('dir /b *.*') do (
   echo !time!
)


Variables in batch that use the %var% naming convention are replaced with their actual values when the script is run. Any variable that is inside of parentheses (for loops, if blocks, multiline output redirection, etc.) will not update while the script is running unless you include the line setlocal enabledelayedexpansion in your script and use the !var! convention for those variables.

darioit
Posts: 230
Joined: 02 Aug 2010 05:25

Re: Update variable in a For loop

#3 Post by darioit » 14 Oct 2015 02:10

Good now works, many Thanks

10:09:28.74
10:09:29.75
10:09:30.79
10:09:31.83
10:09:32.86
10:09:33.90
10:09:34.94
10:09:35.99

Squashman
Expert
Posts: 4484
Joined: 23 Dec 2011 13:59

Re: Update variable in a For loop

#4 Post by Squashman » 14 Oct 2015 07:05

As Jeb told you last year in this thread of yours.
viewtopic.php?f=3&t=5844

Post Reply