NT Batch: Variables in FOR DO loop

(n/a) / (n/a)
February 15, 2009 at 01:40:57
Specs: Windows XP, (N/A)
I have the a batch file called "Test.bat":

---------------Test.bat----------------
SETLOCAL EnableDelayedExpansion

SET LIST=Apple Orange

SET NAME=XXXXX

FOR %%G IN (%LIST%) DO (
SET NAME=%%G
START /WAIT CMD /C "printname !NAME!"
ECHO !NAME!
SET NAME=!NAME! is a fruit
START /WAIT CMD /C "printname !NAME!"
ECHO !NAME!
)

ENDLOCAL
-----------End of Test.bat-------------

I also have another batch file called "printname.bat" which is called by test.bat:
-------------printname.bat-------------
ECHO %1
PAUSE
----------End of printname.bat---------

When I execute test.bat, this is the output I see on the main window:
----------------OUTPUT----------------
Apple
Apple is a fruit
Orange
Orange is a fruit
------------End of OUTPUT-------------

This is, however, not the problem.

Each loop has two calls to printname.bat, where each call to printname,bat is spawned in separate windows. The variable %NAME% is passed in to printname.bat. In each of the loops, both the calls to printname.bat show only "Apple" or "Orange". When the variable is changed to "Apple is a fruit" or "Orange is a fruit", I do not see the changed string being displayed in the separate command windows which are launched by the lines "start /WAIT cmd /C ...".

What do I need to do to be able to get the separate command windows to show the updated variable?


See More: NT Batch: Variables in FOR DO loop

Report •


#1
February 15, 2009 at 01:48:35
START /WAIT CMD /C "printname !NAME!"
This is the most awesomest way to do:
call printname %%G

I do not see the changed string being displayed in the separate command windows
%1 = Apple
%2 = is
%3 = a
%4 = fruit
%* = Apple is a fruit

Or add quotes in the main script:
%1 = "Apple is a fruit"


Report •

#2
February 15, 2009 at 02:13:49
The reason I use "START /WAIT CMD /C ..." is because I want that part to be spawned in a separate shell window. It is done intentionally.

However, I cannot see the updated !NAME! variable being displayed in the second call to printname.bat in the loop.

Any ideas how I can get the spawned windows to display the updated variable contents?


Report •

#3
February 15, 2009 at 02:33:23
That's pretty much what the other 2/3 of my post was about.

EDIT: Or, if you need it spelled out, change your second script to read:

ECHO %*
PAUSE


Report •

Related Solutions

#4
February 15, 2009 at 13:24:03
Why not do away with printname.bat and just use:

START /WAIT CMD /C "echo !NAME!&&pause"


Report •

#5
February 15, 2009 at 17:26:22
Razor2.3 -
EDIT: Or, if you need it spelled out, change your second script to read

As you said, your first post spelt out the solution, but my eyes did not catch it. Thanks for pointing it out to me. Not sure how I missed that. :P


Report •


Ask Question