Super User is a question and answer site for computer enthusiasts and power users. Join them; it only takes a minute:

Sign up
Here's how it works:
  1. Anybody can ask a question
  2. Anybody can answer
  3. The best answers are voted up and rise to the top

i have the following Problem with the way the cmd Interpreter works with Variables. I can´t get it working. Can you tell me the trick ?

Problem: I call a Subroutine with an Argument in Batch-File. Depent on what Value the Argument is, the Subroutine dynamicaly builds a String in a Variable. That Variable should be used in the Main-Batch.

@echo off
set globalvar=text_two,text_one

FOR %%U IN (%globalvar%) DO (
call :SUBROUTINE %%U
echo Variable DYNAMIC after Subroutine: %dynamic%
)

goto :END

:SUBROUTINE
::This Subroutine should Build the VARIABLE depended on the Argument
echo Dynamic in SUB1: %1
IF /I %1==text_one (set dynamic=dynamic_text_example_one)
IF /I %1==text_two (set dynamic=dynamic_text_example_two)
goto:EOF


:END

Output of this Sript executed Twice:

Dynamic in SUB1: text_two
Variable DYNAMIC after Subroutine:
Dynamic in SUB1: text_one
Variable DYNAMIC after Subroutine:

Dynamic in SUB1: text_two
Variable DYNAMIC after Subroutine: dynamic_text_example_one
Dynamic in SUB1: text_one
Variable DYNAMIC after Subroutine: dynamic_text_example_one

I expected the following output, but how ??

Dynamic in SUB1: text_two
Variable DYNAMIC after Subroutine: dynamic_text_example_two
Dynamic in SUB1: text_one
Variable DYNAMIC after Subroutine: dynamic_text_example_one

Dynamic in SUB1: text_two
Variable DYNAMIC after Subroutine: dynamic_text_example_two
Dynamic in SUB1: text_one
Variable DYNAMIC after Subroutine: dynamic_text_example_one

Can you help me ? regards morlogg

share|improve this question
up vote 4 down vote accepted

Use delayed expansion, i.e. put

setlocal enabledelayedexpansion

at the start of your batch and then use

FOR %%U IN (%globalvar%) DO (
  call :SUBROUTINE %%U
  echo Variable DYNAMIC after Subroutine: !dynamic!
)

%dynamic% is expanded the instant cmd parses the complete for loop; therefore it cannot pick up a value you set in the subroutine (which obviously happens inside the loop).

share|improve this answer
    
Wow, Thanks a lot ! That is exactly what i am looking for. It is working. – Morlogg Apr 1 '11 at 13:28
    
this saved my bacon, thanks – snowcrash09 May 25 '11 at 9:59

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .