Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Recovering from an invalid GOTO command in a Windows batch file

Tags:

batch-file

In a Windows batch file, I am taking an optional parameter that allows the caller to jump to the middle of the batch file and resume from there.

For example:

if [%1] neq [] (
echo Starting from step %1
goto %1
if %errorlevel% neq 0 goto error
)

:step1

:step2

...

goto end
:error
echo Error handler
...

:end

If the supplied parameter is not a valid label, the batch file immediately exits with the error The system cannot find the batch label specified.

Is there any way for me to handle this error and either execute my error handler block, or resume execution of the entire batch file, as if no parameter had been supplied?

like image 897
Daniel Fortunov Avatar asked May 07 '09 14:05

Daniel Fortunov


People also ask

How do I use goto in a batch file?

Usage: GOTO can only be used in batch files. After a GOTO command in a batch file, the next line to be executed will be the one immediately following the label. The label must begin with a colon [:] and appear on a line by itself, and cannot be included in a command group.

What does goto do in CMD?

The goto command moves a batch file to a specific label or location, enabling a user to rerun it or skip other lines depending on inputs or events.

What is goto EOF in batch file?

At the end of your subroutine, you can jump to the end of the batch file (so that execution falls off the end) by doing a goto :eof . In other words, goto :eof is the return statement for batch file subroutines.

How do you loop or start a batch file over after it has completed?

Pressing "y" would use the goto command and go back to start and rerun the batch file. Pressing any other key would exit the batch file.


2 Answers

You could try using findstr on the batch locating the goto target:

findstr /r /i /c:"^:%1" %0>nul
if errorlevel 1 goto error

It's a bit of a hack, but should work.

like image 110
Joey Avatar answered Jan 04 '23 11:01

Joey


call :label spits out the error doesn't spit out an error when stderr is redirected (thanks, Johannes), and doesn't appear to change the error level, but continues with the batch file. You could set a variable after a label to indicate whether execution got that far.

@echo off
call :foo 2>nul
echo %errorlevel%
:bar
echo bar

yields

C:\>test.cmd
The system cannot find the batch label specified - foo
1
bar
C:\>
like image 24
Anonymous Avatar answered Jan 04 '23 10:01

Anonymous