0

I am running the following Windows batch script a.bat on Windows Server 2016:

@ECHO OFF

IF NOT DEFINED XXX_ROOT (
    SET "XXX_ROOT=D:\Programs\XXX"
    SET XXX_ROOT
    ECHO."XXX_ROOT %XXX_ROOT%"
)

IF EXIST "%XXX_ROOT%\" (
    ECHO."Found the dir %XXX_ROOT%"
) ELSE (
    ECHO."ERROR:XXX_ROOT %XXX_ROOT% is not a directory"
    EXIT /B 13
)

SET XXX_ROOT

The following is a fresh session of the CMD shell:

Microsoft Windows [Version 10.0.14393]
(c) 2016 Microsoft Corporation. All rights reserved.

First, note that the directory D:\Programs\XXX exists on disk:

18:42:43.54 D:\src\trunk> dir D:\Programs\XXX
 Volume in drive D is UserProfile
 Volume Serial Number is A4EF-EDF6

 Directory of D:\Programs\XXX

05/14/2019  06:42 PM    <DIR>          .
05/14/2019  06:42 PM    <DIR>          ..
               0 File(s)              0 bytes
               2 Dir(s)  40,632,406,016 bytes free

Now, note that there are no environment variables starting with XXX:

18:42:52.58 D:\src\trunk> set XXX
Environment variable XXX not defined

We execute the script and get the following output:

18:44:01.07 D:\src\trunk> call Scripts\a.bat
XXX_ROOT=D:\Programs\XXX
"XXX_ROOT "
"Found the dir D:\Programs\XXX"
XXX_ROOT=D:\Programs\XXX

After the script executed, my environment has been updated with the new variables XXX_ROOT:

18:44:10.55 D:\src\trunk> set XXX
XXX_ROOT=D:\Programs\XXX

Now the question: The script clearly sets XXX_ROOT and is able to correctly resolve the condition IF EXIST "%XXX_ROOT%\", and nevertheless the operator to print its value after the original set shows an inconsistency:

  • SET XXX_ROOT seems to display XXX_ROOT=D:\Programs\XXX
  • but ECHO."XXX_ROOT %XXX_ROOT%" displays "XXX_ROOT " as if the variable %XXX_ROOT% has empty string value inside the script.

Why does this happen, and how do I access the correct value of %XXX_ROOT% inside the script?

Mofi
  • 46,139
  • 17
  • 80
  • 143
gt6989b
  • 4,125
  • 8
  • 46
  • 64
  • Why the second set command? – UnhandledExcepSean May 14 '19 at 23:19
  • 4
    Possible duplicate of [Variables are not behaving as expected](https://stackoverflow.com/questions/30282784/variables-are-not-behaving-as-expected) In your first `IF` block, you have `SET` the variable `XXX_ROOT`, however as the block is parsed in one go, the variable was `NOT DEFINED` and therefore had no value at that time. You should therefore enable delayed expansion and use `!XXX_ROOT!`, or use a pseudo `CALL`, i.e. `CALL ECHO."XXX_ROOT %%XXX_ROOT%%"`. – Compo May 14 '19 at 23:27
  • @Compo thank you so much, if you write it up as an answer, I will accept it. Or i can delete the question as duplicate, if you like. – gt6989b May 15 '19 at 00:27
  • Leave it as a duplicate so searchers can find it. – Noodles May 15 '19 at 05:04

0 Answers0