3

In a subroutine, %0 expands to the subroutine name, not the script name. Is there a ligitimate way to still access the script name, or should I pass it as an argument?

@echo off

call :subroutine %~f0 my parameters
exit /b

:subroutine
shift
echo Script name is %0
echo Parameters: %1 %2
exit /b

I want the call statement to be just

call :subroutine my parameters
utapyngo
  • 6,946
  • 3
  • 44
  • 65

3 Answers3

4

In a function you need to add at least one modifier to %~0.

call :test
exit /b

:test
echo 0   %0    - shows "test"
echo ~0  %~0   - shows "test"
echo ~f0 %~f0  - shows the batch name (full path)
exit /b
jeb
  • 78,592
  • 17
  • 171
  • 225
  • Thank you. I have already noticed this after reading http://stackoverflow.com/questions/14559789/printing-a-paragraph-in-windows-batch. – utapyngo Feb 10 '13 at 12:32
2

I believe %~nx0 will give you filename with extension and %~n0 will give you just the file name...

TrevorPeyton
  • 629
  • 3
  • 10
  • 22
1

I prefer using this at the top of my scripts:

set "This=%~dpnx0"

This way you still keep the full path of the currently running script. If there's the need to get just the name of the script you can use a FOR /F loop to extract it:

set "This=%~dpnx0"
echo This=%This%
for /F %%I in ('echo.%This%') do set "Name=%%~nxI"
echo Name=!Name!
Andreas
  • 5,393
  • 9
  • 44
  • 53
  • I used to think that global variables are bad. But it looks like this is not the case. – utapyngo Feb 10 '13 at 11:06
  • @utapyngo: This is basically true but since there is no way to define constant values in Windows batch scripting I think that this is an acceptable exception. :) – Andreas Feb 10 '13 at 11:17
  • 1
    Well, I guess you could just do `set "Name=%~nx0"` at the beginning. :) At the very least, your loop seems a bit overkill, you could have a simpler one: `for %%I in ("%This%") do set "Name=%%~nxI"`. – Andriy M Feb 10 '13 at 11:45