Page 1 of 1

%~x0 is Null if Batch is executed with quotes.

Posted: 23 Jan 2016 10:16
by Meerkat
Dealing with Bath Hybrids, I see that if Batch file is executed in CMD with quotes, %x~0 is blank. This is a serious thing if Batch file names have spaces, because we use quotes on it.

Example: Sample session...
CMD.EXE wrote:C:\>type NoSpace.bat
@echo off
echo(%~f0

C:\>NoSpace
C:\NoSpace.bat

C:\>ren NoSpace.bat "With Space.bat"

C:\>"With Space"
C:\With Space <<<No Extensions.

C:\>

Assuming that we will not edit the file name, how will get the REAL full path of the Batch file with quotes? Thanks!

Meerkat

Re: %~x0 is Null if Batch is executed with quotes.

Posted: 23 Jan 2016 11:52
by ShadowThief
The extension appears if you include the extension when you call the script.

Image

Re: %~x0 is Null if Batch is executed with quotes.

Posted: 23 Jan 2016 12:02
by penpen
This may help you (tested on Win 8.1, 32 bit):

Code: Select all

@echo off
call :showName
goto :eof

:showName
echo(%~f0
goto :eof


penpen

Re: %~x0 is Null if Batch is executed with quotes.

Posted: 23 Jan 2016 19:42
by foxidrive
Or use this:

Code: Select all

@echo off
for %%a in ("%~f0") do echo "%%~xa" - "%%~a"
pause

Re: %~x0 is Null if Batch is executed with quotes.

Posted: 23 Jan 2016 19:54
by dbenham
foxidrive wrote:Or use this:

Code: Select all

@echo off
for %%a in ("%~f0") do echo "%%~xa" - "%%~a"
pause

That is of no help, as I expected. The extension is still missing if the called script is launched with quotes around the name.

I believe the only solution is to CALL into a subroutine as penpen has shown.


Dave Benham

Re: %~x0 is Null if Batch is executed with quotes.

Posted: 24 Jan 2016 00:10
by foxidrive
I initially had this: and removed the .* after a brief test - my test was flawed.

This does work - but it relies on not have extra files with the same name.

Code: Select all

@echo off
for %%a in ("%~f0.*") do echo "%%~xa" - "%%~a"
pause

Re: %~x0 is Null if Batch is executed with quotes.

Posted: 25 Jan 2016 03:15
by mcnd
Maybe this (http://stackoverflow.com/a/26851883/2861476) could help. As far as I know, the penpen's answer is the only reliable way to ensure you retrieve a valid reference to the current batch file.

Re: %~x0 is Null if Batch is executed with quotes.

Posted: 25 Jan 2016 05:10
by Meerkat
Thanks everyone! :D

Meerkat