Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to get value return from a function within a loop?

Tags:

batch-file

cmd

I am trying to work out how to test the return value of a function call within a loop and breaks the loop if function returns a specific value.

The follow piece of batch script is my attempt, the function return expected value on the first 2 function calls. When the call is made within a loop, I cannot figure out how to test the return value. Please point me to a direction on how to test the function return value within the loop.

SET var1=2
SET var2=0
CALL :FUNC %var1 var2
ECHO var2 is: %var2%

REM ============================

SET var1=6
SET var2=0
CALL :FUNC %var1 var2
ECHO var2 is: %var2%

REM ============================

SETLOCAL EnableDelayedExpansion
SET list=1 0 3 4
FOR %%n IN (%list%) DO (
    CALL :FUNC %%n rtn
    IF !rtn! == 0 (
        GOTO DONE
    )
)
ECHO rtn is: %rtn%

: DONE
PAUSE
GOTO :eof


REM %1 is an in parameter
REM %2 is an out parameter
: FUNC
SETLOCAL EnableDelayedExpansion
SET var=%1
EndLocal & SET %2=%var% & GOTO :eof
like image 238
simon Avatar asked Feb 28 '26 17:02

simon


1 Answers

I can't see any problems with your loop, but with your function.
You only need to change the last line to (the quotes are new):
EndLocal & SET "%2=%var%" & GOTO :eof

Without the quotes, you always appended a single space to your return value,
therefore the IF !rtn! == 0 ( was always false

like image 102
jeb Avatar answered Mar 02 '26 06:03

jeb



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!