Andreas
Andreas

Reputation: 5599

Windows batch variable expansion not working properly

I'm facing some unexpected output when I store the driveletter from %0 into a variable.

The following snippet is run 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 prints the correct value for Target but not for the current directory:

Target:  C:
Current: C:\Temp\Test

Expected output:

Target:  C:
Current: C:\

I also tried the same code with delayed expansion but this didn't work either. Can anybody explain what's going on here?

Upvotes: 3

Views: 456

Answers (3)

PA.
PA.

Reputation: 29339

Your problem is not with variable expansion, but with pushd behavior.

this scenario may explain how pushd (or cd btw) works

C:\>cd temp
C:\temp>_

now %cd% is c:\temp. If you "move" to another drive

C:\temp>e:

and try

E:\>pushd c:
C:\temp>_

see that now %cd% is back C:\temp, and not to C:\ as you were expecting.

but

C:\temp>e:
E:\>pushd c:\
C:\>_

brings %cd% to C:\ as you were expecting.

so, your .BAT file may be simply written as

pushd %~d0\

Upvotes: 4

jeb
jeb

Reputation: 82307

Why do you expect Current: C:\?
You runs the script from C:\Temp\Test.
So it's correct that %CD% expands to C:\Temp\Test.

If you expecte that %CD% should change as you use PUSHD %target% you need to split the line, or use delayed expansion for !CD!, as at first the complete line is parsed and the percent expansion is done, before your PUSHD is executed.

The other problem is that pushd C: doesn't change the path, as C: is a relative path, you need to to use C:\

@echo off
set "Target=%~d0\"
setlocal EnableDelayedExpansion
echo Target:  %Target%
pushd %Target% && echo Current: !CD! || echo Failed to change dir^^!

Upvotes: 1

Loïc MICHEL
Loïc MICHEL

Reputation: 26150

I cant explain you this behaviour but you can mimic it using :

pushd %Target%
if %ERRORLEVEL%==0 (echo Current: %CD%) else (echo Failed to change dir!)

Upvotes: 0

Related Questions