heredoc for Windows batch?

Viewed 24125

Is there a way of specifying multiline strings in batch in a way similar to heredoc in unix shells. Something similar to:

cat <<EOF > out.txt
bla
bla
..
EOF

The idea is to create a customized file from a template file..

19 Answers

Not as far as I know.

The closest I know of is

> out.txt (
    @echo.bla
    @echo.bla
    ...
)

(@ prevents the command shell itself from printing the commands it's running, and echo. allows you to start a line with a space.)

Yes, very possible. ^ is the literal escape character, just put it before your newline. In this example, I put the additional newline in as well so that it is properly printed in the file:

@echo off
echo foo ^

this is ^

a multiline ^

echo > out.txt

Output:

E:\>type out.txt
foo
 this is
 a multiline
 echo

E:\>

Expanding on ephemient post, which I feel is the best, the following will do a pipe:

(
    @echo.line1
    @echo.line2 %time% %os%
    @echo.
    @echo.line4
) | more

In ephemient's post he redirected at the beginning, which is a nice style, but you can also redirect at the end as such:

(
    @echo.line1
    @echo.line2 %time% %os%
    @echo.
    @echo.line4
) >C:\Temp\test.txt

Note that "@echo." is never included in the output and "@echo." by itself gives a blank line.

In a pinch, I use the following method (which doesn't diminish any other methods, this is just a personal preference):

I use a for loop through a set of strings:

for %%l in (
    "This is my"
    "multi-line here document"
    "that this batch file"
    "will print!"
    ) do echo.%%~l >> here.txt
  • Doesn't require a subroutine, easy to remember and execute.
  • Doesn't require a temporary file.
  • Works inside a batch script.
  • Works with embedded variables.
  • However: if you have double quotes in your lines, the method no longer works...

Here is another practical example from the script I'm currently working on:

:intc_version:
for %%l in (
    "File         : %_SCRIPT_NAME%"
    "Version      : %_VERSION%"
    "Company      : %_COMPANY%"
    "License      : %_LICENSE%"
    "Description  : %_DESCRIPTION%"
    ""
) do echo.%%~l
exit /B 0

In a .bat file:

(
@echo.bla
@echo.bla
@echo...
) > out.txt

then

type out.txt

produces

bla
bla
..

A bit messier, having to put @echo. at the beginning of each line, but it does basically what you want: The ability to roll a dependancy file into the script file itself.

There are a lot of other solutions, but all of those require adding a bunch more code to do basically the same thing in a neater way. In one case, even requiring a whole other .bat file as a new dependancy!

Props to B.Reynolds, my answer was inspired by theirs.

Related