0

I want a value to be returned from a subroutine/function which I can use for further processing.

Here, I want "rtn" value to be returned properly from SUB_ONE function. I am getting value ""(NULL) even after script gets into else loop and set %~1=0 inside SUB_ONE.

Code Snippet:

set rtn=""

FOR /L %%i IN (0, 1, 3) do (
   call :SUB_ONE rtn
   echo "Value of rtn is %rtn%   
   if %rtn% NEQ "" ( goto :nextScript )     ## Here, rtn value is not returned as 0 from subroutine even after entering else loop in SUB_ONE function 
   echo "Completed wait for %%i time";
   if %%i == "3" ( goto :nextScript )
 )

:SUB_ONE
 bjobs -J main_jobs |  (set /p myVar= )
 if %errorlevel% equ 0 (
    echo  jobs are still there. Waiting for some more time
   sleep 9
 ) else (
     echo jobs are finished
     echo Triggering another job now
     set %~1=0
     echo %rtn% is rtn value 
)
exit /B 0

Here, rtn value is not set to 0 inside the for loop, and the condition 'if %rtn% NEQ ""' is never getting true even after it should be. I mean script enters the else loop inside :SUB_ONE, prints statements, set %~1=0, and here on echo %rtn%, I get value 0. But, when the function is exited, it must return value of rtn as 0, but it isn't. And if %rtn% NEQ "" ( goto :nextScript ) is not called (the %rtn% value is still NULL). I would want rtn at line 'if %rtn% NEQ "" ( goto :nextScript )' to be 0.

Please help.

Thanks!

AskQuestionsP
  • 153
  • 1
  • 9
  • 1
    The variable `rtn` has already the correct value, but you can't use it with `%rtn%` in a block – jeb Dec 21 '21 at 07:17
  • How can I use it then? – AskQuestionsP Dec 21 '21 at 07:41
  • It's explained in the linked answer, use delayed expansion `!rtn!` that evalues at runtime not at parse time like `%rtn%`. And don't forget to enable delayed expansion before – jeb Dec 21 '21 at 07:42
  • enable delayed expansion should be added where? Inside :SUB_ONE, or at the top of the script, or inside for loop ? – AskQuestionsP Dec 21 '21 at 07:44
  • You should read the answer [Variable behaviour in Windows batch files](https://stackoverflow.com/a/25874045/463115) – jeb Dec 21 '21 at 07:46

0 Answers0