1

I am trying to make a batch file that creates another batch file (Compile.bat) and need to echo the %errorlevel% variable into Compile.bat, but since it's a global variable when it is called is uses current value.

This is the code

ECHO if NOT "%errorlevel%"=="0" PAUSE >> .\%name%\Compile.bat

But Compile.bat receives

if NOT "0"=="0" PAUSE 

Is there a way to stop it from thinking %errorlevel% is a variable?

Adk9p
  • 15
  • 3
  • 1
    The outer brackets for your comparisons are not needed. You can just use double quotes. `ECHO if NOT "%%errorlevel%%"=="0" PAUSE >> .\%name%\Compile.bat` – Squashman Apr 04 '18 at 21:03
  • [Is there a way to prevent percent expansion of env variable in Windows command line?](https://stackoverflow.com/q/33016094/995714) – phuclv Apr 06 '18 at 01:28

2 Answers2

1

You have to escape the errorlevel variable with double %% like this:

ECHO if NOT "%%errorlevel%%"=="0" PAUSE >> .\%name%\Compile.bat

I think this is what you wanted:

if NOT "%errorlevel%"=="0" PAUSE
Adk9p
  • 15
  • 3
Streamfighter
  • 454
  • 4
  • 15
  • 3
    Your explanation is not generic enough. The issue is the percent symbols. Not the variable. If you need to echo a percent symbol to another file you always double the percent symbol. – Squashman Apr 04 '18 at 21:01
0

Here's some helper code for you.

@Echo Off
Set "name=SomeName"
Set "variable=Value"
Rem Write to Compile.bat
Echo Press any key to write to Compile.bat
Pause > Nul
(
    Echo @Echo Off
    Echo %%variable%% = %variable%
    Echo Pause
) > "%name%\Compile.bat"
Echo Finished writing to Compile.bat
Timeout 3 /NoBreak > Nul
Rem Rest of code below here
Compo
  • 36,585
  • 5
  • 27
  • 39