Teodor Vecerdi
Teodor Vecerdi

Reputation: 376

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.

Upvotes: 1

Views: 281

Answers (2)

user6250760
user6250760

Reputation:

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.

Upvotes: 2

Compo
Compo

Reputation: 38604

As you appear only to be copying the contents of several files to a single output file you could probably simplify things a little too.

@Echo Off
If "%~1"=="" Exit/B
Set/P "outputFile= Output File: "
Type %* 2>Nul >"%outputFile%"
Echo( Finished.
Pause

Ensuring the validity of any passed arguments and input string is your responsibility.

You could even possibly bypass the input parameters:

@Echo Off
Set/P "outputFile= Output File: "
Type mod*.txt 2>Nul >"%outputFile%"
Echo( Finished.
Pause

Upvotes: 1

Related Questions