You are not logged in.

#1 18 May 2016 18:43

donjlutz
New Member
Registered: 18 May 2016
Posts: 1

Returning from sub-routines

Ok, it's a personal issue, but I always hated returning from a called subroutine with a goto. I mean, the behavior is not really that of a goto, since it will return to different locations depending on where it was called. I can live with the desired behavior being observed when reaching the end of file... but "goto :eof" still looks like a goto. My old solution was a compromise. I defined a label ":Return", placed it just before a label ":Fini" and both were just before the end of the file. Hence, exits from the command script were always done via "Goto :Fini" and returns from subroutines were always done with a "Goto :Return"

But it still was a goto...

Then, I had my ah-hah moment. I included the following statement at the beginning of my command shell script "set Return=goto :EOF". Now all sub-routines are exited with the command %Return%.  No, I don't think my OCD is out of control. It helps me explain my scripts to a non-scripting audience.

Hope this helps (see example below)!

@setlocal
@echo off
set return=goto :EOF

call :SendMessage
call :SendMessage
call :SendMessage

@endlocal
pause
exit


:SendMessage
	@echo "Hi!"
%return%

Offline

#2 18 May 2016 18:49

Shadow Thief
Member
Registered: 12 Jul 2012
Posts: 205

Re: Returning from sub-routines

You can also use exit /b instead of goto :eof so that you don't need to use a goto at all.

Offline

#3 18 May 2016 18:58

DigitalSnow
Member
From: United States
Registered: 27 Dec 2012
Posts: 24

Re: Returning from sub-routines

Big +1 to what Shadow Thief said.  Use exit /b

@echo off

call :SendMessage "Hello"
call :SendMessage "World"
call :SendMessage "Goodbye"

pause
exit


:SendMessage <Message>
	echo "%~1"
exit /b

Last edited by DigitalSnow (18 May 2016 18:59)

Offline

#4 19 May 2016 08:04

bluesxman
Member
From: UK
Registered: 29 Dec 2006
Posts: 1,129

Re: Returning from sub-routines

exit /b also allows you to set a return code (errorlevel).  I suppose you could adapt your method and do this:

@setlocal
@echo off
set return=exit /b

call :SendMessage
call :SendError || echo Failed

@endlocal
pause
exit

:SendMessage
	@echo Hi!
%return%

:SendError
	@echo Error
%return% 1

Last edited by bluesxman (19 May 2016 08:05)


cmd | *sh | ruby | chef

Offline

Board footer

Powered by