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 displayXXX_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?