Why this works?

Discussion forum for all Windows batch related topics.

Moderator: DosItHelp

Post Reply
Message
Author
Aacini
Expert
Posts: 1914
Joined: 06 Dec 2011 22:15
Location: México City, México
Contact:

Why this works?

#1 Post by Aacini » 25 Sep 2015 10:47

At this SO question there is this code:

Code: Select all

@echo off
cls
setlocal
(
echo c123abc
echo c234abc
echo c345abc
echo cfcd123
)>%temp%\_file.tmp

set mypath=c:\xxx\sys\exe\folder\folder\
echo:
setlocal enabledelayedexpansion
for /f "delims=" %%a in (%temp%\_file.tmp) do (
    set "sid=%%a"
    rem :: set "sid=!sid:~1,3!"
    set mypath=%mypath:xxx=!sid:~1,3!%
    echo sid: !sid!, servername: !sid:~1,3!, newpath: !mypath!
)
endlocal
echo Completed.
exit /b 0

that produce this output:

Code: Select all

sid: c123abc, servername: 123, newpath: c:\123\sys\exe\folder\folder\
sid: c234abc, servername: 234, newpath: c:\234\sys\exe\folder\folder\
sid: c345abc, servername: 345, newpath: c:\345\sys\exe\folder\folder\
sid: cfcd123, servername: fcd, newpath: c:\fcd\sys\exe\folder\folder\
Completed.

All that I know about variable expansions (normal and delayed) say me that this line:

Code: Select all

    set mypath=%mypath:xxx=!sid:~1,3!%

should fail: the %mypath:whichever% expansion should be done just one time when the FOR was parsed. However, accordingly to the results obtained, is seems that the %mypath:....% expansion is executed each time that the !sid:~1,3! expansion is done, and after it!!! :shock:

EDIT: A simple test of my own:

Code: Select all

@echo off
setlocal EnableDelayedExpansion

set "dummy=X"
for /L %%i in (1,1,9) do (
   set "array[%%i]=%dummy:X=!random!%
)
set array

What is happening here?

Antonio

jeb
Expert
Posts: 1055
Joined: 30 Aug 2007 08:05
Location: Germany, Bochum

Re: Why this works?

#2 Post by jeb » 25 Sep 2015 11:34

Hello Aacini,

thanks for an interesting question.
I was also suprised, but with ECHO ON I got it!

So in the first parse the percent expansion takes effect, but it only replaces the xxx with !sid:~1,3!.

And that will be expand in each single loop!

Aacini
Expert
Posts: 1914
Joined: 06 Dec 2011 22:15
Location: México City, México
Contact:

Re: Why this works?

#3 Post by Aacini » 25 Sep 2015 14:29

Thanks a lot, jeb, for not answer "it is obvious", but now that I understood what happen here, I think "it is obvious" :D

Antonio

Post Reply