I know how to return a value from a function in the same batch file, but I've found some problems in returning a value from a different batch file. Here is an example:
File 1.cmd
SETLOCAL ENABLEEXTENSIONS
SETLOCAL ENABLEDELAYEDEXPANSION
set number=1
call 2.cmd
echo. %number%
ENDLOCAL
exit /B
File 2.cmd
SETLOCAL ENABLEEXTENSIONS
SETLOCAL ENABLEDELAYEDEXPANSION
ENDLOCAL & set number=2
exit /B
And the output is still 1. Is there any solution?
LittleBobbyTables was on the correct track.
Your use of two SETLOCAL but only 1 ENDLOCAL causes the variable to be set, but then the definition is lost because there is an additional implicit ENDLOCAL when the batch exits at EXIT /B. All SETLOCAL are ended whenever a batch or function terminates. Your code simply needs an additional ENDLOCAL before you set the value.
SETLOCAL ENABLEEXTENSIONS
SETLOCAL ENABLEDELAYEDEXPANSION
ENDLOCAL & ENDLOCAL & set number=2
exit /B
But it is extremely rare that enableExtensions is needed since extensions are always enabled by default. You should be able to drop SETLOCAL ENABLEEXTENSIONS and use a single ENDLOCAL.
If for some reason you really do need to enable extensions, then you can use both options on a single SETLOCAL and still need only one ENDLOCAL
SETLOCAL ENABLEEXTENSIONS ENABLEDELAYEDEXPANSION
ENDLOCAL & set number=2
exit /b
I'm having a hard time explaining it properly, but the combination of both
SETLOCAL ENABLEEXTENSIONS
SETLOCAL ENABLEDELAYEDEXPANSION
in your 2.cmd
file are causing a delay in the evaluation of the variable.
If either is individually enabled, %number%
should still be set to 2, but together, %number%
will be set to 1.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With