0

How do I solve delayed variable assignment?

(I'm making the term delayed variable assignment up, because it seems like a reasonable descriptive phrase).

Example Batch Script Code script.bat:

@echo off
set mylocation=%CD%
echo mylocation %mylocation%
echo CD %CD%

Actual Output

C:> script.bat
mylocation
CD C:\

C:>

What I want it to do (or thought it would do)

C:> script.bat
mylocation C:\
CD C:\

C:>

Edit (changed): If I echo %mylocation% in command prompt after the script ends it has a value.

C:>echo %mylocation%
C:\

C:>

Edit: This is the original Code, and you can view the youtube video https://youtu.be/jQzEFD3yISA - where I try to show as much detail as possible so that, everything is exact.

@echo off

set natasha_command=%1

if %natasha_command% == start (
    set mylocation=%CD%
    echo mylocation %mylocation%
    echo CD %CD%
)

goto :eof
  • 1
    Not an answer obviously but your script works on my machine. I get that output that you expected. – Loocid Jun 02 '15 at 02:39
  • So if it works perfectly fine for you, is there anything else that could cause it, to sparingly not operate occasionally? – Firstname Lastname Jun 02 '15 at 03:59
  • 1
    You need to show us exactly the code you are using by cutting and pasting. `olddir` is not mentioned in the snippet you've provided, so it seems you're showing different code from that which you are using. It's important to aste in-context, since for instance a stray space could cause the problem you've described or more likely you're setting and displaying a variable in a conditional-bracket. – Magoo Jun 02 '15 at 04:49
  • Does [this answer](http://stackoverflow.com/a/18464353/19719) help? – indiv Jun 02 '15 at 04:55
  • Ok, I'm going to post the code, and upload a video to youtube to show it. Cheers. – Firstname Lastname Jun 02 '15 at 05:52
  • the description in indiv's link is correct, but maybe [this answer](http://stackoverflow.com/a/30284028/2152082) is better understandable. – Stephan Jun 02 '15 at 07:22
  • Cheers indiv, cheers Stephan! – Firstname Lastname Jun 03 '15 at 03:46

1 Answers1

4

Within a block statement (a parenthesised series of statements), the entire block is parsed and then executed. Any %var% within the block will be replaced by that variable's value at the time the block is parsed - before the block is executed - the same thing applies to a FOR ... DO (block).

Hence, IF (something) else (somethingelse) will be executed using the values of %variables% at the time the IF is encountered.

Two common ways to overcome this are 1) to use setlocal enabledelayedexpansion and use !var! in place of %var% to access the changed value of var or 2) to call a subroutine to perform further processing using the changed values.

Note therefore the use of CALL ECHO %%var%% which displays the changed value of var. CALL ECHO %%errorlevel%% displays, but sadly then RESETS errorlevel.

Magoo
  • 77,302
  • 8
  • 62
  • 84