Google Groups no longer supports new Usenet posts or subscriptions. Historical content remains viewable.
Dismiss

In second batch file, find the name of its caller

177 views
Skip to first unread message

John Gray

unread,
Sep 7, 2017, 3:35:29 AM9/7/17
to
In a called batch file, I would like to determine the name (as in %~n0) of the batch file which called itme, but without passing this name as a parameter.
Is this possible?
In second batch file,
I've done some searching in this group but can only find the suggestion to give the name of the calling batch file as a parameter.

Trivial example:

:: Caller.bat
call called.bat
exit /b

:: Called.bat
:: some code to find the name of the calling batch file
echo Called.bat was called by %name-of-caller%
goto :eof

JJ

unread,
Sep 7, 2017, 6:44:26 AM9/7/17
to
If without passing some information as a batch file parameter is your only
requirement, then you can use either environment variable or a file instead.
e.g.

::Caller.bat
::using environment variable
set caller=%~n0
call called.bat
goto :eof

::Called.bat
::using environment variable
echo Called.bat was called by %caller%
goto :eof

::Caller.bat
::using file
>"%temp%\caller.tmp" echo %~n0
call called.bat
goto :eof

::Called.bat
::using file
for /f "delims=" %%A in (%temp%\caller.tmp) do (
echo Called.bat was called by %%A
)
goto :eof

John Gray

unread,
Sep 7, 2017, 8:26:53 AM9/7/17
to
Thank you very much! It's so very obvious once you say it!

To my surprise, that environment variable is available both before and after setlocal in the called.bat file.

::Caller.bat
::using environment variable
set caller=%~n0
call called.bat %parm1% %parm2% %parm3%
goto :eof

::Called.bat
::using environment variable
echo %%caller%% before setlocal contains %caller%
setlocal
echo %%caller%% after setlocal contains %caller%
echo Parameters are %1 %2 %3
echo Called.bat was called by %caller%
...
endlocal
goto :eof

B00ze

unread,
Sep 7, 2017, 11:01:02 PM9/7/17
to
On 2017-09-07 08:26, John Gray <jgq...@gmail.com> wrote:

> To my surprise, that environment variable is available both before and after setlocal in the called.bat file.

SETLOCAL creates a COPY of the environment when it is executed. So the
value is still there, but if you modify it the new value will not
propagate to the calling environment.

Regards,

--
! _\|/_ Sylvain / B00...@hotmail.com
! (o o) Member:David-Suzuki-Fdn/EFF/Red+Cross/SPCA/Planetary-Society
oO-( )-Oo I'm a lawyer. Honest? No, the usual kind.

0 new messages