I'm on Windows 10 Enterprise x64. I have the following hierarchy of directories with a BAT file at the innermost level:
C:\
dir\
my files\
run.bat
The BAT file contains the following lines:
@pushd %~dp0
@echo %~dp0
@popd
(the meaning and use of %~dp0 is explained in the help topic for /? and in this answer)
If I run the BAT file from a command prompt whose current directory is C:\dir\my files, then I get a very reasonable result:
C:\dir\my files>run.bat
C:\dir\my files\
But if I invoke it from the parent directory C:\dir, I get:
C:\dir>"my files"\run.bat
C:\dir\my files\my files"\
Huh? Note that the innermost directory name is duplicated and there are some stray characters "\ at the end. Let's try it in a different way:
C:\dir>"my files\run.bat"
C:\dir\my files\my files\
The stray characters are gone, but the directory name is still duplicated. What is an explanation for this? How can I modify the BAT file so that it gives the same output no matter from which directory it has been invoked?
Of course, my real scenario is more complicated than this simplified version. The value of %~dp0 is concatenated with other strings, assigned to environment variables, passed as an argument to other scripts, etc.