Search code examples
for-loopif-statementbatch-filevariablescmd

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


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.


Solution

  • The IF is detected by the parser 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.

    That could be solved by changing the text in code.file to if !var! == 0301 (echo Yay)
    This works, because the delayed expansion happens after the percent expansion

    Or a much simpler solution:

    copy code.file tmp.bat
    call tmp.bat
    del tmp.bat