GOTO

Direct a batch program to jump to a labelled line.

Syntax
      GOTO label

      GOTO:eof

Key
   label   A predefined label in the batch program.
           Each label must be defined on a line by itself, beginning with
           a colon and ending with either a space, a colon or a CR/LF.

   :eof    This predefined label will exit the current subroutine or script.

Using GOTO:eof will transfer execution to the end of the current batch file or the end of the current subroutine. Unlike Exit /b the goto:eof will automatically set an errorlevel.
Although undocumented, GOTO :MySubroutine has the same effect as GOTO MySubroutine

Examples:

A simple goto jump:

GOTO MySubroutine
   Echo this wont display
goto:eof

:MySubroutine
   Echo this is a subroutine

Use the %1 parameter to jump:

IF %1==12 GOTO MySubroutine 
   Echo the input was NOT 12
goto:eof 
 
:MySubroutine
   Echo the input was  12
goto:eof

Use a variable as a label:
   
CHOICE /C:01 /m choose [Y]yes or [N]No 
   goto sub_%ERRORLEVEL% 
   
   :sub_0 
   Echo You typed Y for yes
goto:eof 

:sub_1
   Echo You typed N for no
goto:eof
 
Use a variable as a  comment
In this example the COPY command will only run if the parameter "Update" is supplied to the batch:
   
@Echo Off 
Setlocal
SET _skip=
IF /I NOT %1==Update SET _skip=:: 
   
%_skip% COPY x:\update.dat 
%_skip% echo Update applied 
 ...

Bugs

Using GOTO within parenthesis - including FOR and IF commands - will break their context:

@echo off
if A equ A (
 	    GOTO :EXAMPLE_LABEL
 	    :EXAMPLE_LABEL
    rem
) else (
 	echo You didn't expected to see this,did you?
) 

An alternative is to replace the GOTO with a CALL to a subroutine. The subroutine can contain GOTO statements as they will be safely outside the parenthesis.

GOTO breaks the & and && redirection operators.

If GOTO a non existent label is used in conjunction with a negative conditional execution, the line containing the GOTO will be executed, but the rest of the Batch file is cancelled:

goto :non_existent_label || Echo This line will run anything except GOTO ,SHIFT ,SETLOCAL , ENDLOCAL , CALL
:SUBROUTINE echo This will be never displayed.

GOTO is an internal command. If Command Extensions are disabled GOTO will no longer recognise the :EOF label

“GOTO... how bad can it be??...” ~ XKCD

Related:

EXIT - Quit the current script/routine and set an errorlevel.
IF - Conditionally perform a command.
CALL - Call one batch program from another.
Powershell: While (condition) {action} else {action}
Equivalent bash command:case - Conditionally perform a command.


© Copyright SS64.com 1999-2015
Some rights reserved