1

A very simple question to understand semantic of a batch running. please look at this piece of code

FOR /F %%x IN (file.txt) DO (
if /i "%~1"=="%%x" goto :label
if /i "%~1"=="%%xYZ" goto :label
)
:label
......

After jumping to the label, Is then batch come back to the for loop automatically? If else, is there a means to do it come back to the for loop? Thanks

new
  • 1,109
  • 5
  • 21
  • 30

3 Answers3

2

The goto command will jump to a label and will jump out of the loop in your example, however, you should be able to use call, which can be used to call a label as a subroutine:

for /F %%x in (file.txt) do (
if /i "%~1"=="%%x" call :label
if /i "%~1"=="%%xYZ" call :label
)

:: end script here
exit /b 0

:label

From the call page on the Microsoft TechNet site:

call [[Drive:][Path] FileName [BatchParameters]] [:label [arguments]]

...

: label : Specifies the label to which you want a batch program control to jump. By using call with this parameter, you create a new batch file context and pass control to the statement after the specified label. The first time the end of the batch file is encountered (that is, after jumping to the label), control returns to the statement after the call statement...

Stuart Wakefield
  • 6,294
  • 24
  • 35
  • The batch programming may be more complex sometimes! thanks for your assistance, your explanation helps too much! – new May 18 '13 at 00:08
  • You can use `goto :eof` instead of `exit /b 0`, too (just learned from [Rob van der Woude](http://www.robvanderwoude.com/goto.php)). – CodeFox Nov 07 '13 at 15:45
0

If label is after your for loop in the batch file then, no, the batch file won't go back to the for loop

Daniel Flippance
  • 7,734
  • 5
  • 42
  • 55
  • is there a means to do it come back to the for loop? Thanks – new May 17 '13 at 23:11
  • It does not matter where the label is. Even if the label is within the loop, a GOTO will immediately terminate the loop. – dbenham May 17 '13 at 23:21
  • I think you mean you want to call a function from within the for loop and then have the loop continue where it left off. If that function is complex you might want to put it in another batch file, otherwise you can put the code inside your if statement inside the for loop. This post shows how to do an OR statement in your IF: http://stackoverflow.com/questions/2143187/logical-operators-and-or-in-dos-batch – Daniel Flippance May 17 '13 at 23:25
0

And you can't access the variable either. I suggest calling another batch file and paasing %%x to it. That is the closest you can get to a subroutine.

Moby Disk
  • 3,761
  • 1
  • 19
  • 38
  • Does it change something if I replace the goto:label by the call :label, with the label that is defined into the same batch file? Thanks – new May 17 '13 at 23:25