Search code examples
batch-filenested-loops

Batch nested loop doesn't work


I'm trying to make a mod loader for a game in batch but I can't get it to work with a nested loop.

The command used is this loadMods.bat mod1.txt mod2.txt ... modN.txt

This is the code I'm using

setlocal EnableDelayedExpansion
set /p outputFile="Output File:"

for %%x in (%*) do (
    echo Applying mod from file %%x
    for /f "delims=" %%y in (%%x) do echo %%y >> %fileOutput%
)
echo Finished.
pause

The second loop works fine if it's outside the first loop but when I use nested loops I get an The syntax of the command is incorrect. error on the second loop.


Solution

  • As @SomethingDark said, this is caused by a simple typographical issue.

    for /f "delims=" %%y in (%%x) do echo %%y >> %fileOutput%
    

    The variable fileoutput was undefined, making the CMD.EXE sees:

    for /f "delims=" %%y in (%%x) do echo %%y >>
    

    and it cannot find an argument after >>, causing the error.


    By the way, when debugging batch files, I'd recommend:

    • remove @echo off
    • run script from CMD.exe

    These method shows exactly which command(s) go wrong, making debugging easier.