Home > OS >  Batch: How to do returning if then statements in for command?
Batch: How to do returning if then statements in for command?

Time:11-27

I am attempting to figure out a way to do returning if then statements in the for command, here's the code so far:

We have a file called: File.cfg with multiple numbers (no more than 6 numbers):

1
3
4
6
2
5

Setting those numbers as variables:

setlocal enabledelayed expansion
setlocal
set /a count=1
for /F "usebackq delims=" %%a in ( File.cfg ) do (
    set line!count!=%%a
    set /a count =1
)

Then attempting to do a returning if then operations:

set /a count=0
echo 1 > list.txt
:Loop
set /a count =1
echo %count% > list.txt
FOR /F "usebackq delims= " %%a in (list.txt) do (
    echo !line%%a!
    if %%a==7 goto :eof
    if !line%%a!==1 goto 1
    if !line%%a!==2 goto 2
    if !line%%a!==3 goto 3
    if !line%%a!==4 goto 4
    if !line%%a!==5 goto 5
    if !line%%a!==6 goto 6
)

Example of the goto #'s

:1
code
code
code
goto loop

Though in the end, the batch program ends prematurely, mainly at count 1.

Final output results:

 ( echo !line1!
 if 1 == 7 goto :eof
 if !line1! == 1 goto 1
 if !line1! == 2 goto 2
 if !line1! == 3 goto 3
 if !line1! == 4 goto 4
 if !line1! == 5 goto 5
 if !line1! == 6 goto 6
)
1

CodePudding user response:

Not sure why you have the complicated code unless you are trying to do a proof of concept on something. In my experience the easiest way to achieve your desired outcome is to do this.

@echo off

for /F "usebackq delims=" %%a in ("File.cfg") do CALL :%%a

REM END OF MAIN Functions below
GOTO :EOF

:1
ECHO IN 1
GOTO :EOF

:2
ECHO IN 2
GOTO :EOF

REM Shortened for brevity

The code above will output

IN 1
IN 3
IN 4
IN 6
IN 2
IN 5

If you really want to use array variables then again the easiest solution is the following code.

@echo off

setlocal enabledelayedexpansion

set "count=0"
for /F "usebackq delims=" %%a in ("File.cfg") do (
    set /a "count =1"
    set "line!count!=%%a"
)

FOR /L %%G IN (1,1,%count%) DO CALL :!line%%G!

REM END OF MAIN Functions below
GOTO :EOF

:1
ECHO IN 1
GOTO :EOF

:2
ECHO IN 2
GOTO :EOF

REM Shortened for brevity 

The aforementioned code will also output

IN 1
IN 3
IN 4
IN 6
IN 2
IN 5
  • Related