Unexpected duplicate directory names after expanding `%~dp0` in a BAT file
This is a known bug/design deficiency within cmd.exe - %~dp0
and variants can give the wrong result if the path to the batch script was quoted.
There is a work-around. You can reliably get the value from within a CALLed subroutine (note that at least one modifier like ~d
, ~f
etc. must be used, else you get the subroutine :label
)
@echo off
setlocal
pushd %~dp0
echo From main fails: "%~dp0"
call :test
popd
exit /b
:test
echo From subroutine OK: "%~dp0"
-- SAMPLE OUTPUT --
d:\dir>"my files\test.bat"
From main fails: "d:\dir\my files\my files\"
From subroutine OK: "d:\dir\my files\"