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
7
  • 1
    Not an answer obviously but your script works on my machine. I get that output that you expected. Commented Jun 2, 2015 at 2:39
  • So if it works perfectly fine for you, is there anything else that could cause it, to sparingly not operate occasionally? Commented Jun 2, 2015 at 3: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. Commented Jun 2, 2015 at 4:49
  • Does this answer help? Commented Jun 2, 2015 at 4:55
  • Ok, I'm going to post the code, and upload a video to youtube to show it. Cheers. Commented Jun 2, 2015 at 5:52

1 Answer 1

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.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.