There are multiple ways to create a Batch file from inside another one. The methods that use echo batch code
requires to escape the special characters that may appear in the "batch code". There are other methods that consist in read lines from the Batch file itself and then output such lines to the created file; in this case, the lines may have pure Batch code even if they contains special characters.
The method you used in your example is similiar to Unix heredoc feature, that is:
tr a-z A-Z << END_TEXT
one two three
uno dos tres
END_TEXT
There are several ways to simulate a "Unix heredoc" in Batch; for example this one:
@echo off
rem Definition of heredoc macro
setlocal DisableDelayedExpansion
set LF=^
% Don't remove this line 1/2 %
% Don't remove this line 2/2 %
set ^"\n=^^^%LF%%LF%^%LF%%LF%^^"
set heredoc=for %%n in (1 2) do if %%n==2 (%\n%
for /F "tokens=1,2" %%a in ("!argv!") do (%\n%
if "%%b" equ "" (call :heredoc %%a) else call :heredoc %%a^>%%b%\n%
endlocal ^& goto %%a%\n%
)%\n%
) else setlocal EnableDelayedExpansion ^& set argv=
rem Heredoc syntax:
rem
rem %%heredoc%% :uniqueLabel [outfile]
rem contents
rem contents
rem ...
rem :uniqueLabel
rem For example:
%heredoc% :endBatch file.bat
@echo off
echo hallo
exit /B
:endBatch
echo Calling created file:
call file.bat
echo Return from created file
goto :EOF
rem Definition of heredoc subroutine
:heredoc label
set "skip="
for /F "delims=:" %%a in ('findstr /N "%1" "%~F0"') do (
if not defined skip (set skip=%%a) else set /A lines=%%a-skip-1
)
for /F "skip=%skip% delims=" %%a in ('findstr /N "^" "%~F0"') do (
set "line=%%a"
echo(!line:*:=!
set /A lines-=1
if !lines! == 0 exit /B
)
exit /B