I have doubts about how to use "for, if, echo, goto" in batch

I have the following batch script but it doesn't go to label:

for /f %%i in ('some commands') do echo %%i IF %%i == A (goto :A) else (goto :end) IF %%i == B (goto :B) else (goto :end) :A echo "OK A" :B echo "OK B" :end echo "It is not A or B" exit 

If the output of the command is the letter A, then go to the label A, if it is B then to the B and if it is "empty" or "something else" to go to end. But I can't make it go to labels :A or :B

I tried it with quotes or square brackets and I don't get the desired result:

IF [%%i] == [] goto :end IF [%%i] == [A] goto :A IF [%%i] == [B] goto :B 

or

IF "%%i" == "" goto :end IF "%%i" == "A" goto :A IF "%%i" == "B" goto :B 

thanks in advace

1 Answer

FOR variables are only valid in the loop itself.

But your loop contains only one statement echo %%i.
Therfor your IF %%i ... can 't work.

If you want the complete block to be a part of the loop, enclose it in brackets

for /f %%i in ('some commands') do ( echo %%i IF %%i == A (goto :A) else (goto :end) IF %%i == B (goto :B) else (goto :end) ) 

But now there is another problem, execution of GOTO inside a loop cancels the loop.

Better use CALL

for /f %%i in ('some commands') do ( echo Loop: "%%i" IF "%%i" == "A" call :A IF "%%i" == "B" call :B ) exit /b :A echo "OK A" exit /b :B echo "OK B" exit /b 
1

Your Answer

Sign up or log in

Sign up using Google Sign up using Facebook Sign up using Email and Password

Post as a guest

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

You Might Also Like