1

Hello Batch File experts,

I wrote this piece of code which will print the Latest file version present in the folder in comparison to file name sent as argument, however these line seems to work accordingly when I remove the outer for loop, which I designed to loop as many time as CLI arguments.

FOR /f %%f IN ('DIR /b %%a.*.zip') DO @SET last=%%f
ECHO %last%

Full code :

cd C:\Users\batch\Desktop\test
chdir


set arg1=%1
set arg2=%2
set list=%arg1% %arg2%


(for %%a in (%list%) do (


FOR /f %%f IN ('DIR /b %%a.*.zip') DO @SET last=%%f

ECHO %last%

)) 

pause

what am I missing here because of which variable last is not set with value when outer loop is present which works perfectly without it.

Thanks,

  • The echoing of your variable is in the wrong place, you've got a variable named last which is only technically last at the end, not throughout. _(it is technically only echoing every file and setting to the last modified matching file of the latest found argument)_. – Compo Nov 30 '16 at 13:39
  • Possible duplicate of [Use a variable in a 'for' loop](http://stackoverflow.com/questions/6373307/use-a-variable-in-a-for-loop) – aschipfl Nov 30 '16 at 13:54
  • Too many people use for loops as the default coding method with no thought as to possible alternatives, there's no reason why alternatives ignoring `!last!` or `call %%last%%` should not be proposed. – Compo Nov 30 '16 at 13:57

2 Answers2

0

You need to use delayed expansion (about ten thousand SO items on this) or use a subroutine or

call echo %%last%%
Magoo
  • 77,302
  • 8
  • 62
  • 84
0

Might I suggest you use SHIFT instead:

@Echo Off
SetLocal
If %1'==' Exit/B
If /I Not "%CD%"=="%USERPROFILE%\Desktop\test" (
    PushD "%USERPROFILE%\Desktop\test" 2>Nul&&(Set _=PopD)||Exit/B)
:Loop
For %%A In ("%~1*.zip") Do Set "last=%%A"
Echo=%last%
Shift
If Not %1'==' GoTo Loop
%_%
EndLocal
Timeout -1

This of course means that you are free to use it with more than two arguments!

Compo
  • 36,585
  • 5
  • 27
  • 39