Take the 2-minute tour ×
Super User is a question and answer site for computer enthusiasts and power users. It's 100% free, no registration required.

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

1 Answer 1

up vote 3 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

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

Not the answer you're looking for? Browse other questions tagged or ask your own question.