5.1.3. Examples of GOTO commandΒΆ

Using GOTO and lables, in a batch file, we can jump to different parts of a batch file.

Note

For advanced help, see GOTO, CMD and IF.

Special meaning of :EOF for batch files when we use GOTO.

When we run command as shown below:

1echo This will be printed.
2goto :EOF
3
4echo EOF means End Of File.
5echo But this lines will not be printed.
6echo Because we have already exited from
7echo this file above.

The output is:

This will be printed.

Sample script which shows usage of ERRORLEVEL as 0 with IF. and GOTO.

When we run command as shown below:

 1REM Just run DIR Command. No need to print anything on console.
 2REM So that ERRORLEVEL will be set to 0.
 3
 4DIR > NUL
 5
 6IF %ERRORLEVEL% EQU 0 GOTO :IS_0
 7
 8:IS_0
 9    ECHO It is 0
10    GOTO :DONE
11
12:IS_NOT_0
13    ECHO It is not 0
14    GOTO :DONE
15
16:DONE
17    ECHO End of File.

The output is:

It is 0
End of File.

Sample script which shows GTR condition for IF. and GOTO.

When we run command as shown below:

 1dir /b is_missing_file
 2
 3IF %ERRORLEVEL% GTR 0 goto :NOT_OKAY
 4
 5:NOT_OKAY
 6    echo Something failed
 7    goto :DONE
 8
 9:OKAY
10    echo It was fine
11    goto :DONE
12
13
14:DONE
15    ECHO End of File.

The output is:

Something failed
End of File.