Using the for /f command

Discussion forum for all Windows batch related topics.

Moderator: DosItHelp

Post Reply
Message
Author
gotouser
Posts: 7
Joined: 26 Feb 2018 07:36

Using the for /f command

#1 Post by gotouser » 28 Feb 2018 10:25

So, I was wondering if it was possible to use the for /f command to insert commands written in a text file into a batch script, for example:

This is saved as hello.txt:
echo hello

This is saved as hello.bat
@echo off
for /f "tokens=* delims= " %%a in (hello.txt) do (
%%a
)
pause

This works, but if i modify it like this:

This is saved as hello.txt
:loop
%NAME%, do you want to say hello? (Y=Yes)
set /p ANSWER=
if %ANSWER%==Y goto hello
echo You didn't say hello.
pause
goto loop

:hello
echo hello
pause
goto loop

This is saved as hello.bat:
@echo off
set NAME=Tom
for /f "tokens=* delims= " %%a in (hello.txt) do (
%%a
)

It doesn't work. It says

"%NAME%, do you want to say hello? (Y=Yes)

If you type anything:
The command "if" is either mispelled or could not be found.
You didn't say hello.
Press any key to continue...

It also says that "loop" has not been found. I was just trying things while learning how to use for commands. Does anyone know if you could make that work?

penpen
Expert
Posts: 2009
Joined: 23 Jun 2013 06:15
Location: Germany

Re: Using the for /f command

#2 Post by penpen » 03 Mar 2018 10:06

You can't define "extern" labels (from "hello.txt") within a for loop of (another) batch file ("hello.bat"), because the "loop body" (== "(\n%%a\n)" in C-style) is computetd in RAM only, while the "goto" command searches the active batch file ("hello.bat") for that label.
The IF/REM/FOR-commands should not work, because they are computed within another parser phase; see:
https://stackoverflow.com/questions/409 ... ts/4095133.

I also son't see the need for executing a whole text file that way:
I think it is much simpler, if you copy the text file into a batch file, and then execute it using call.

Something like this "hello.bat" that wamts the "hello.txt" to be executed:

Code: Select all

@echo off
copy "hello.txt" "hello.txt.bat"
call "hello.txt.bat"
del "hello.txt.bat"
goto :eof
penpen

Post Reply