3

I have just noticed a very strange behavior of %0 in a .bat file called via %PATH%.

Somewhere in %PATH%, (say, C:\InPath), create file xxx.bat containing:

@echo off
echo this = %~f0

In a different directory, somewhere not in %PATH%, (e.g. C:\NotInPath), create file yyy.bat containing:

@echo off
call "xxx.bat"

Change the working directory to anything, (e.g. C:\SomewhereElse) and run yyy.bat. What I would expect to see is:

this = C:\InPath\xxx.bat

What I actually get is:

this = C:\SomewhereElse\xxx.bat

The problem is apparently caused by the quotes in the call, because if I change the call line in yyy.bat to call xxx.bat, I get the expected output.

I wonder what could be the reason for this difference in behavior and if there is something I can do to get the correct output even with the quotes - e.g. to facilitate scripts containing a space character. Without executing a new instance of cmd.exe, that is - I need the called script to set some environment values to be read by the caller script.

Compo
  • 36,585
  • 5
  • 27
  • 39
pepak
  • 712
  • 4
  • 13
  • Please try this. in `xxx.bat` `echo local = %~0` and in `yyy.bat` do `echo remote %~0 && call xxx.bat` and show me the output. – Gerhard Mar 22 '19 at 09:05
  • @GerhardBarnard: `remote = C:\NotInPath\yyy.bat`, `local = xxx.bat` (no path, %0 in a CALL basically copies the calling string, i.e. when I remove the `.bat` extension from the call, I get `local = xxx`) – pepak Mar 22 '19 at 09:44

1 Answers1

3

You can fix it with

@echo off
echo This can be wrong %~f0

call :fixIt
exit /b

:fixIt
echo FixIt %~f0

Link to a good explanation from MC ND
SO:What is the reason for batch file path referenced with %~dp0 sometimes changes on changing directory?

jeb
  • 78,592
  • 17
  • 171
  • 225
  • Perfect. This solution works. However, I still wonder: Just what is the point of this strange behavior. It seems to be a bug in CMD, but perhaps Microsoft has some reason for it? – pepak Mar 22 '19 at 10:39
  • @pepak [dbenham](https://stackoverflow.com/users/1012053/dbenham) or I wrote something about `%~0` somewhere on stackoverflow or dostips.com, my problem is to search for such keywords. Typically Dave wrote better and longer texts than me – jeb Mar 22 '19 at 10:42