GOTO - CMD
Overview
The GOTO
command in Windows Command Prompt (CMD) allows you to change the flow of execution to a specific section within a batch script, usually marked by a label. This command is primarily used for creating conditional or repetitive logic structures, enabling more dynamic and flexible script behavior.
Syntax
The basic syntax for using GOTO
is:
GOTO label
label
: This is the target label within the script where execution will jump to. The label must be defined somewhere in the batch file prefixed with a colon:
(e.g.,:Start
).
Options/Flags
The GOTO
command does not have additional options or flags. Its functionality is solely determined by the label to which it directs the flow of execution.
Examples
-
Basic Navigation: Jumping to a labeled section of the script to repeat or skip actions.
@ECHO OFF :begin ECHO Hello, this part will run repeatedly. GOTO begin
-
Conditional Logic: Using
GOTO
withIF
statements to execute different sections of code based on specific conditions.@ECHO OFF SET /P USERINPUT=Enter Y to continue, N to exit: IF %USERINPUT%==Y GOTO CONTINUE IF %USERINPUT%==N GOTO END :CONTINUE ECHO You chose to continue! GOTO END :END ECHO Goodbye!
Common Issues
- Label not found: If the label specified in the
GOTO
command does not exist in the batch file, CMD will return an error stating it could not find the batch label. Ensure that all labels are correctly spelled and defined in the script. - Endless Loop: Improper use of
GOTO
can cause scripts to enter an endless loop. This can be avoided by setting proper exit conditions in loops.
Integration
GOTO
can be effectively combined with other CMD commands for more complex scripting scenarios:
-
Loop with Delay: Integrating
GOTO
withTIMEOUT
for delays in loops.@ECHO OFF :LOOP ECHO Looping... TIMEOUT /T 5 GOTO LOOP
-
Error Checking: Using
GOTO
with error checks.@ECHO OFF COPY file1.txt file2.txt IF ERRORLEVEL 1 GOTO ERRORHANDLING ECHO File copied successfully! GOTO END :ERRORHANDLING ECHO An error occurred during copying. GOTO END :END
Related Commands
- IF: Used for conditional branching in scripts.
- CALL: Calls one batch program from another, sometimes used with
GOTO
for more structured script flow. - EXIT: Exits the command interpreter or the current batch script, often used after a
GOTO
to terminate the script correctly.
For more information, refer to the official Microsoft documentation.