Home > database >  Batch, How do I execute code stored in a variable or txt file?
Batch, How do I execute code stored in a variable or txt file?

Time:08-17

How can I execute code saved in a variable? I'm trying to execute an if statement that I have saved in another file (that must remain a text file). Clues on how to execute an if statement just from a variable might help, as I assume the problem is that it can't read the %%s.

Text file contains:

if %var%==0301 (echo Yay) 

Batch file contains:

for /f "tokens=*" %%s in (code.file) do (
%%s
)

This normally executes the code in code.file by setting everything in code.file to the variable %%s and then executing the variable.

The result is this: 'if' is not recognized as an internal or external command, operable program or batch file.

This method works for executing echo and set, but I need it to work for if.

CodePudding user response:

The major problem at hand is that the command interpreter particularly handled the commands if, for and rem: These commands are recognized earlier than every other one, even before for meta-variables like %%s become expanded. Therefore, these commands are no longer detected after expansion of %%s.

Refer to: How does the Windows Command Interpreter (CMD.EXE) parse scripts?
According to this, said commands are detected during Phase 2, while expansion of for meta-variables happens in Phase 4. Other commands are found later in Phase 7.

A possible way to work around that is to use a sub-routine, which %-expansion occurs in, which happens in Phase 1, hence before recognition of the three special commands:

for /f "tokens=*" %%s in (code.file) do (
    rem // Execute the read command in a sun-routine:
    call :SUB %%s
)
goto :EOF

:SUB
rem // Take the whole argument string as a command line:
%*
goto :EOF

CodePudding user response:

The IF is detected by the parser only in phase2 only, but %%s will be expanded in a later phase.

You need to use a percent expansion for it, like in this sample

for /f "tokens=*" %%s in (code.file) do (
  set "line=%%s"
  call :executer
)
exit /b

:executer
%line%
exit /b

But for your sample: if %var%==0301 (echo Yay)
It will never say Yay, because %var% will never be expanded.

This is because %line% is already a percent expansion, it will not work recursively.

  • Related