Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Batch - How to return a value from a batch file?

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?

like image 628
Charles Avatar asked Aug 18 '12 11:08

Charles


2 Answers

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
like image 153
dbenham Avatar answered Sep 28 '22 18:09

dbenham


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.

like image 37
LittleBobbyTables - Au Revoir Avatar answered Sep 28 '22 19:09

LittleBobbyTables - Au Revoir