Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to exit a batch function?

Tags:

batch-file

So I wanted to do something like this:

@echo off
echo Before
call :test
echo After
pause

:test
echo I'm in test!
:end

echo I shouldn't be here...

Such that it would call test after saying Before and before saying After. However, it keeps just saying I shouldn't be here before saying After! Now, it's not necessarily a problem in this example, but when I have a whole bunch of functions, it can be quite an issue. Can anyone please help me? Thanks! :)

like image 669
Matias Avatar asked Jan 13 '18 00:01

Matias


1 Answers

Batch has no concept of "sections", "functions", "procedures" or "paragraphs". A label is simply a reference point. Execution does not stop when a label is reached, it simply continues through, line by line, until it reaches end-of-file, a CALL , a GOTO or an EXIT. This is why you get the message you mention - and why the I'm in test! and the "rogue" message appear after your pause (which you wouldn't see if you are executing the batch by "click"ing it)

You need to goto :eof after completing the mainline, otherwise execution will continue through the subroutine code. :EOF is a predefined label understood by CMD to mean end of file. The colon is required.

You can use goto :eof to terminate a subroutine (reaching end-of-file terminates the routine and returns to the statement after the call) OR you can use exit or exit /b [n] as explained in the documentation (se exit /? from the prompt.

The downside of using exit is that it will terminate the cmd instance if executed when the routine hasn't been called - ie. it's part of the main routine - consequently, goto :eof is more popular.

like image 76
Magoo Avatar answered Sep 22 '22 20:09

Magoo