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! :)
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 call
ed - ie. it's part of the main routine - consequently, goto :eof
is more popular.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With