문제

I am having a weird issue with a windows batch file.

Here is a sample

call:label1
echo check1

:label1
echo label1

:label2
echo label2

The output I am expecting is

>label1
>check1

But the batch is running both labels and I am getting the following output:

>label1
>label2
>check1

I am calling the batch file from cmd. What am I doing wrong?

도움이 되었습니까?

해결책

Labels just define a starting point. When a call :label instruction is used, called code is executed from this starting point until reaching the end of the batch file. So, to end a subroutine before the next one is reached (and return to the calling point), you will need to add an exit /b or goto :eof or whatever other jump to the end of the batch file, as

call:label1
echo check1
goto endOfWork

:label1
echo label1
goto :eof

:label2
echo label2
exit /b

:endOfWork

:eof is an implicit label that points to the EndOfFile, and does not need to be declared.

So, goto :eof is a jump to the end of the file.

exit /b is just the same, a jump to the end of file.

The :endOfWork is a user defined label (the same you are using in your code) than i'm using to get the same result without using the previous instructions.

다른 팁

My issue here is that I need the next line, that is echo check1 to run after the label1 call. I cannot goto :eof or exit /b in label1. My workaround here is:

call:label1
echo check1

:label1
echo label1

:label2
if %1 =="running" (
   echo label2
)

Therefore, to call label2 you will have to pass the parameter call :label2 running. Calling label1 will not run anything in the if clause of the label 2. Looks a bit dirty to me but I could not find any way round.

라이센스 : CC-BY-SA ~와 함께 속성
제휴하지 않습니다 StackOverflow
scroll top