Get the name of a batch file from a subroutine

In a subroutine,% 0 expands the subroutine name, not the script name. Is there a ligitive way to access the script name or 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 operator to be just

call :subroutine my parameters

      

+3


source to share


3 answers


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

      

+4


source


I believe% ~ nx0 will give you the filename with extension, while% ~ n0 will only give you the filename ...



+2


source


I prefer to use this at the top of my scripts:

set "This=%~dpnx0"

      

This way you still keep the full path to the current script run. If you only need to get the name of the script, you can use a FOR / F loop to retrieve it:

set "This=%~dpnx0"
echo This=%This%
for /F %%I in ('echo.%This%') do set "Name=%%~nxI"
echo Name=!Name!

      

+1


source







All Articles