Search code examples
batch-filepathvariable-expansion

Incorrect %0 in a .BAT file


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.


Solution

  • 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?