Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What's wrong with Windows bat recursion?

I am trying to write Windows batch commands. Here is my test function:

@echo off & setlocal EnableDelayedExpansion

echo hi

call :minus 1
echo %result%
call :minus 2
echo %result%
call :minus 3
echo %result%
call :minus 4
echo %result%
call :minus 5
echo %result%

PAUSE
goto :eof

:minus
setlocal

set num=%1
if %num% equ 1 endlocal & set result=%num% & goto :eof

set /a num=%num%-1
call :minus %num%

endlocal
goto :eof

As expected, for everything greater than and equal to 1, the result will be 1:

hi
1
1
1
1
1
Press any key to continue . . .

But when I change the first call to call :minus 2 (the rest is the same):

echo hi

call :minus 2
echo %result%
call :minus 2
echo %result%
call :minus 3
echo %result%
call :minus 4
echo %result%
call :minus 5
echo %result%

PAUSE
goto :eof

The output is:

hi
ECHO is off.
ECHO is off.
ECHO is off.
ECHO is off.
ECHO is off.
Press any key to continue . . .

What does ECHO is off. mean?

like image 982
midnite Avatar asked Aug 01 '26 03:08

midnite


1 Answers

Well, if you call minus with 2, result will never be set (the if %num% equ 1 won't evaluate to true), hence you call echo without any parameter, which will result in ECHO is off. as output due to the @echo off at the top of your script.

like image 130
hbrgnr Avatar answered Aug 02 '26 19:08

hbrgnr



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!