Windows batch variable expansion does not work as expected
I am faced with some unexpected result when I store a floppy with %0
in a variable.
The following snippet is executed from C: \ Temp \ Test :
@echo off
for %%I in ("%~0") do set "Target=%%~dI"
echo Target: %Target%
pushd %Target% && echo Current: %CD% || echo Failed to change dir!
This outputs the correct value for Target
, but not for the current directory:
Target: C:
Current: C:\Temp\Test
Expected Result:
Target: C:
Current: C:\
I also tried the same code with expansion delay, but that didn't work either. Can anyone please explain what is going on here?
source to share
Your problem is not with variable expansion but with behavior pushd
.
this script might explain how it works pushd
(or cd
btw)
C:\>cd temp
C:\temp>_
now %cd%
- c:\temp
. If you move to another drive
C:\temp>e:
and try
E:\>pushd c:
C:\temp>_
see what's %cd%
coming back now c:\temp
, not C:\
as you expected.
but
C:\temp>e:
E:\>pushd c:\
C:\>_
brings %cd%
in C:\
as you expected.
so your .BAT file can simply be written as
pushd %~d0\
source to share
Why do you expect Current: C:\
?
You are running your script from C:\Temp\Test
.
So, believe what %CD%
expands to C:\Temp\Test
.
If you expect what %CD%
should change in use PUSHD %target%
, you need to split the string or use delayed expansion for !CD!
, since full syntactic markup is done first, and percentage expansion is done before yours is executed PUSHD
.
Another problem is that pushd C:
does not change the path since it C:
is a relative path, you need to useC:\
@echo off
set "Target=%~d0\"
setlocal EnableDelayedExpansion
echo Target: %Target%
pushd %Target% && echo Current: !CD! || echo Failed to change dir^^!
source to share