0

I am new in CMD scripting. Please explain what is going on: Script:

FOR %%W IN (
    aaa
    bbb
) DO (
    echo was=%%W 
    set fff=%%W*
    echo new=%fff%    
)

Result:

was=aaa
new=bbb*
was=bbb
new=bbb*

Thanks.

Stephan
  • 53,940
  • 10
  • 58
  • 91

1 Answers1

0

The command interpreter needs to know that variables inside the loop require re-evaluation. Search for and learn about ENABLEDELAYEDEXPANSION.

SETLOCAL ENABLEDELAYEDEXPANSION

FOR %%W IN (
    aaa
    bbb
) DO (
    echo was=%%W 
    set fff=%%W*
    echo new=!fff!
)
lit
  • 14,456
  • 10
  • 65
  • 119
  • Wow! That way works! Thank you a lot. I may use your fix. But I still confused with what happen with my code and why I need to complicate the very simple code with such strange way? – user3994488 Mar 06 '16 at 10:19
  • @user3994488: short demonstration of [delayed expansion](http://stackoverflow.com/a/30284028/2152082). See links in comment there for technical details – Stephan Mar 06 '16 at 10:24
  • Thanks a lot. Is there any more curious things which have to be aware of the regular C, Perl, Python, ... programmer like me? – user3994488 Mar 06 '16 at 13:15
  • yes: batch is not a programming language, but a collection of various utilities. They evolved through decades, and therefore may not have coherent behaviour. That makes each problem a new challenge. – Stephan Mar 06 '16 at 18:05
  • @user3994488 - I would like to slightly disagree with @Stephan. `cmd` is an interpretive programming language, like BASIC, Perl, and Python. That is not to say that it is a good or bad language. The trick is to choose a language appropriate, and available, for the task. – lit Mar 06 '16 at 21:45