setlocal EnableDelayedExpansion
(set \n=^
%=Do not remove this line=%
echo Line1!\n!Line2
echo Works also with quotes "!\n!line2"
First a single linefeed character is created and assigned to the \n-variable.
This works as the caret at the line end tries to escape the next character, but if this is a Linefeed it is ignored and the next character is read and escaped (even if this is also a linefeed).
Then you need a third linefeed to end the current instruction, else the third line would be appended to the LF-variable.
Even batch files have line endings with CR/LF only the LF are important, as the CR's are removed in this phase of the parser.
The advantage of using the delayed expansion is, that there is no special character handling at all.
echo Line1%LF%Line2
would fail, as the parser stops parsing at single linefeeds.
More explanations are at
SO:Long commands split over multiple lines in Vista/DOS batch (.bat) file
SO:How does the Windows Command Interpreter (CMD.EXE) parse scripts?
Edit: Avoid echo.
This doesn't answer the question, as the question was about single echo
that can output multiple lines.
But despite the other answers who suggests the use of echo.
to create a new line, it should be noted that echo.
is the worst, as it's very slow and it can completly fail, as cmd.exe searches for a file named ECHO
and try to start it.
For printing just an empty line, you could use one of
echo,
echo;
echo(
echo/
echo+
echo=
But the use of echo.
, echo\
or echo:
should be avoided, as they can be really slow, depending of the location where the script will be executed, like a network drive.
–
–
–
Then just throw in a %n%
whenever you want a new line in an echo statement. This is more close to your \n
used in various languages.
Breakdown
set n=
sets the variable n
equal to:
^
Nulls out the next symbol to follow:
&
Means to do another command on the same line. We don't care about errorlevel(its an echo statement for crying out loud), so no &&
is needed.
echo.
Continues the echo statement.
All of this works because you can actually create variables that are code, and use them inside of other commands. It is sort of like a ghetto function, since batch is not exactly the most advanced of shell scripting languages. This only works because batch's poor usage of variables, not designating between ints, chars, floats, strings, etc naturally.
If you are crafty, you could get this to work with other things. For example, using it to echo a tab
set t=^&echo. ::there are spaces up to the double colon
–
When echoing something to redirect to a file, multiple echo commands will not work. I think maybe the ">>" redirector is a good choice:
echo hello > temp
echo world >> temp
–
–
–
–
–
–
If anybody comes here because they are looking to echo a blank line from a MINGW make makefile, I used
@cmd /c echo.
simply using echo.
causes the dreaded process_begin: CreateProcess(NULL, echo., ...) failed.
error message.
I hope this helps at least one other person out there :)
–
After a sleepless night and after reading all answers herein, after reading a lot of SS64 > CMD and after a lot of try & error I found:
The (almost) Ultimate Solution
TL;DR
... for early adopters.
:: Sets newline variables for the current user [HKEY_CURRENT_USER\Environment]
setx \n ^&echo(
setx nl ^&echo(
... for the Local Machine
:: Sets newline variables for the local machine [HKEY_LOCAL_MACHINE\SYSTEM\CurrentControlSet\Control\Session Manager\Environment]
setx \n ^&echo( /m
setx nl ^&echo( /m
Why just almost?
It does not work with double-quotes that are not paired (opened and closed) in the same printed line, except if the only unpaired double-quote is the last character of the text, e.g.:
works: ""echo %\n%...after "newline". Before "newline"...%\n%...after "newline"
(paired in each printed line)
works: echo %\n%...after newline. Before newline...%\n%...after newline"
(the only unpaired double-quote is the last character)
doesn't work: echo "%\n%...after newline. Before newline...%\n%...after newline"
(double-quotes are not paired in the same printed line)
Workaround for completely double-quoted texts (inspired by Windows batch: echo without new line):
set BEGIN_QUOTE=echo ^| set /p !="""
%BEGIN_QUOTE%
echo %\n%...after newline. Before newline...%\n%...after newline"
It works with completely single-quoted texts like:
echo '%\n%...after newline. Before newline...%\n%...after newline'
Added value: Escape Character
:: Escape character - useful for color codes when 'echo'ing
:: See https://learn.microsoft.com/en-us/windows/console/console-virtual-terminal-sequences#text-formatting
set ESC=
For the colors see also https://imgur.com/a/EuNXEar and https://gist.github.com/gerib/f2562474e7ca0d3cda600366ee4b8a45.
2nd added value: Getting Unicode characters easily
A great page for getting 87,461 Unicode characters (AToW) by keyword(s): https://www.amp-what.com/.
The Reasons
The version in Ken's answer works apparently (I didn't try it), but is somehow...well...you see:
set NLM=^
set NL=^^^%NLM%%NLM%^%NLM%%NLM%
The version derived from user2605194's and user287293's answer (without anything between '=
' and '^
'):
set nl=^&echo(
set \n=^&echo(
works partly but fails with the variable at the beginning of the line to be echo
ed:
> echo %\n%Hello%\n%World!
echo & echo(Hello & echo(World!
echo is ON.
Hello
World
due to the blank argument to the first echo
.
All others are more or less invoking three echo
s explicitely.
I like short one-liners.
The Story Behind
To prevent set \n=^&echo:
suggested in answers herein echoing blank (and such printing its status) I first remembered the Alt+255 user from the times when Novell was a widely used network and code pages like 437 and 850 were used. But 0d255/0xFF is ›Ÿ‹ (Latin Small Letter Y with diaeresis) in Unicode nowadays.
Then I remembered that there are more spaces in Unicode than the ordinary 0d32/0x20 but all of them are considered whitespaces and lead to the same behaviour as ›␣‹.
But there are even more: the zero width spaces and joiners which are not considered as whitespaces. The problem with them is, that you cannot C&P them since with their zero width there's nothing to select. So, I copied one that is close to one of them, the hair space (U+200A) which is right before the zero width space (U+200B) into Notepad++, opened its Hex-Editor plugin, found its bit representation E2 80 8A
and changed it to E2 80 8B
. Success! I had a non-whitespace character that's not visible in my \n
environment variable.
–
–
–
–
Ken and Jeb solutions works well.
But the new lines are generated with only an LF character and I need CRLF characters (Windows version).
To this, at the end of the script, I have converted LF to CRLF.
Example:
TYPE file.txt | FIND "" /V > file_win.txt
del file.txt
rename file_win.txt file.txt
If one needs to use famous \n in string literals that can be passed to a variable, may write a code like in the Hello.bat script below:
@echo off
set input=%1
if defined input (
set answer=Hi!\nWhy did you call me a %input%?
) else (
set answer=Hi!\nHow are you?\nWe are friends, you know?\nYou can call me by name.
setlocal enableDelayedExpansion
set newline=^
rem Two empty lines above are essential
echo %answer:\n=!newline!%
This way multiline output may by prepared in one place, even in other scritpt or external file, and printed in another.
The line break is held in newline variable. Its value must be substituted after the echo line is expanded so I use setlocal enableDelayedExpansion to enable exclamation signs which expand variables on execution. And the execution substitutes \n with newline contents (look for syntax at help set). We could of course use !newline! while setting the answer but \n is more convenient. It may be passed from outside (try Hello R2\nD2), where nobody knows the name of variable holding the line break (Yes, Hello C3!newline!P0 works the same way).
Above example may be refined to a subroutine or standalone batch, used like call:mlecho Hi\nI'm your comuter
:
:mlecho
setlocal enableDelayedExpansion
set text=%*
set nl=^
echo %text:\n=!nl!%
goto:eof
Please note, that additional backslash won't prevent the script from parsing \n substring.
–
–
–
why not use substring/replace space to echo;
?
set "_line=hello world"
echo\%_line: =&echo;%
Results:
hello
world
Or, replace \n to echo;
set "_line=hello\nworld"
echo\%_line:\n=&echo;%
–
–
–
–
For windows 10 with virtual terminal sequences there exists the means control the cursor position to a high degree.
To define the escape sequence 0x1b, the following can be used:
@Echo off
For /f %%a in ('echo prompt $E^| cmd')Do set \E=%%a
To output a single newline Between Strings:
<nul set /p "=Hello%\E%[EWorld"
To output n
newlines where n
is replaced with an integer:
<nul set /p "=%\E%[nE"
–
–
–
14 years later I recommend to use Powershell instead.
You can even most probably just change the file ending from .bat
to .ps1
and have it working.
Then, you can use
echo "Hello`nWorld"
# or even
echo Hello`nWorld
Tested on Win10.
You can also do Windows-type newlines with echo "Hello`r`nWorld"
.
Source: https://devblogs.microsoft.com/scripting/powertip-new-lines-with-powershell/, it says "Use the `n character".
A lot of confusion within the other answers and comments was due to echo
being available on Windows and Linux.
For linux, you can simply use echo "Hello\nWorld"
to get the same result on most distros.
But still, it's recommended to use printf
in linux scripts.
You can use @echo
( @echo + [space] + [insecable space] )
Note: The insecable space can be obtained with Alt+0160
Hope it helps :)
[edit] Hmm you're right, I needed it in a Makefile, it works perfectly in there. I guess my answer is not adapted for batch files... My bad.
–
Be aware, this won't work in console because it'll simulate an escape key and clear the line.
Using this code, replace <ESC>
with the 0x1b escape character or use this Pastebin link:
:: Replace <ESC> with the 0x1b escape character or copy from this Pastebin:
:: https://pastebin.com/xLWKTQZQ
echo Hello<ESC>[Eworld!
:: OR
set "\n=<ESC>[E"
echo Hello%\n%world!
–
Adding a variant to Ken's answer, that shows setting values for environment variables with new lines in them.
We use this method to append error conditions to a string in a VAR, then at the end of all the error checking output to a file as a summary of all the errors.
This is not complete code, just an example.
@echo off
SETLOCAL ENABLEDELAYEDEXPANSION
:: the two blank lines are required!
set NLM=^
set NL=^^^%NLM%%NLM%^%NLM%%NLM%
:: Example Usage:
Set ErrMsg=Start Reporting:
:: some logic here finds an error condition and appends the error report
set ErrMsg=!ErrMsg!!NL!Error Title1!NL!Description!NL!Summary!NL!
:: some logic here finds another error condition and appends the error report
set ErrMsg=!ErrMsg!!NL!Error Title2!NL!Description!NL!Summary!NL!
:: some logic here finds another error condition and appends the error report
set ErrMsg=!ErrMsg!!NL!Error Title3!NL!Description!NL!Summary!NL!
echo %ErrMsg%
pause
echo %ErrMsg% > MyLogFile.log
Log and Screen output look like this...
–