I have a batch file that computes a variable via a series of intermediate variables:
@echo off
setlocal
set base=compute directory
set pkg=compute sub-directory
set scripts=%base%\%pkg%\Scripts
endlocal
%scripts%\activate.bat
The script on the last line isn’t called, because it comes after endlocal, which clobbers the scripts environment variable, but it has to come after endlocal because its purpose is to set a bunch of other environment variables for use by the user.
How do I call a script who’s purpose is to set permanent environment variables, but who’s location is determined by a temporary environment variable?
I know I can create a temporary batch file before endlocal and call it after endlocal, which I will do if nothing else comes to light, but I would like to know if there is a less cringe-worthy solution.
The
ENDLOCAL & SET VAR=%TEMPVAR%pattern is classic. But there are situations where it is not ideal.If you do not know the contents of TEMPVAR, then you might run into problems if the value contains special characters like
<>&or|. You can generally protect against that by using quotes likeSET "VAR=%TEMPVAR%", but that can cause problems if there are special characters and the value is already quoted.A FOR expression is an excellent choice to transport a value across the ENDLOCAL barrier if you are concerned about special characters. Delayed expansion should be enabled before the ENDLOCAL, and disabled after the ENDLOCAL.
Limitations:
If delayed expansion is enabled after the ENDLOCAL, then the final value will be corrupted if the TEMPVAR contained
!.values containing a lineFeed character cannot be transported
If you must return multiple values, and you know of a character that cannot appear in either value, then simply use the appropriate FOR /F options. For example, if I know that the values cannot contain
|:If you must return multiple values, and the character set is unrestricted, then use nested FOR /F loops:
Definitely check out jeb’s answer for a safe, bullet proof technique that works for all possible values in all situations.
2017-08-21 – New function RETURN.BAT
I’ve worked with DosTips user jeb to develop a batch utility called RETURN.BAT that can be used to exit from a script or called routine and return one or more variables across the ENDLOCAL barrier. Very cool 🙂
Below is version 3.0 of the code. I most likely will not keep this code up-to-date. Best to follow the link to make sure you get the latest version, and to see some example usage.
RETURN.BAT