Home Dashboard Directory Help

Windows shell bug with how %~dp0 is resolved by Rodney Beede



Sign in
to vote
Type: Bug
ID: 617705
Opened: 10/28/2010 12:46:55 PM
Access Restriction: Public
User(s) can reproduce this bug


Windows 7 64-bit Enterprise Edition

When running a .cmd or .bat script and using %~f0 or %~dp0 to resolve the batch script name if the batch script name has spaces (ex: "my script.cmd") and you chdir within the script then further references to %~dp0 will incorrectly resolve to the new cwd instead of the correct batch script location.

This does not happen if the script name has no spaces in it.

Example script below:
@REM When this script is named "test.cmd" (no spaces) it works as expected for the value of %~f0

@REM When this script is named "test with spaces.cmd" it does not work

echo "Stage 1: dp0 == %~dp0"

SET STAGE1=%~dp0

cd "%~dp0"
mkdir TestSubFolder
cd TestSubFolder

echo "Stage 2: dp0 == %~dp0"
echo Should have gotten value %STAGE1%
Sign in to post a comment.
Posted by bcg_cfranz on 3/17/2012 at 8:15 AM
I would expect %~dp0 to always return the Drive\Path\ of folder containing the running script. As stated in the post, I observed it returns the Current Directory once it's been CD'd to in the script, IF the script name contains spaces and otherwise returns the correct value.

However, the Details of this post specify "Windows 7 x64" and that "this is new to most recent version". Whereas, I've just run it in XP SP3 x86 (32-bit) and it behaves the same in both cases.

Sign in to post a workaround.