Echo newline in Bash prints literal \n
Asked Answered
E

25

3503

How do I print a newline? This merely prints \n:

$ echo -e "Hello,\nWorld!"
Hello,\nWorld!
Eartha answered 11/12, 2011 at 21:1 Comment(11)
For those saying "it works for me", the behavior of echo varies quite a bit between versions. Some will even print the "-e" as part of their output. If you want predictable behavior for anything nontrivial, use printf instead (as in @sth's answer).Nardi
I could not get any of the suggestions in this answer working, because, as it turns out, I was attempting to use it in a function that returns a value, and all the echo (and printf) messages in the function were being appended to the return value after being individually stripped of newlines. Here is a question regarding this, with an extremely thorough answer: #27872569 This was like a three hour mystery tour.Greenman
Also notable: in Unix & Linux Stack Exchange, the accepted answer to How to add new lines when using echoBisset
echo -ne "hello\nworld" (you needed the n flag to interpret escapes) - but as others say, different echo commands may have different results!Gratulant
@Gratulant echo -n man page entry on archlinux ` -n do not output the trailing newline` It has nothing to do with interpreting escapesAlrick
@altu, that's correct. The purpose of the -n flag is to use \n within the formatting string. Of course you may decide to keep the trailing \n, but as you are formatting them, it's not unusual to remove them.Gratulant
It works fine in Bash corresponding to Ubuntu MATE 20.04 (Focal Fossa) - Bash version 5.0.17 (GNU bash, version 5.0.17(1)-release (x86_64-pc-linux-gnu))Enfield
Since echo adds a newline by default you could always run echo "Hello," && echo "World!"Eliezer
As search engine hits may include this one (e.g., for "echo Bash no newline"): See "echo -n" prints "-n" (canonical question, despite the title), How can I 'echo' out things without a newline?, and 'echo' newline suppression.Enfield
Just read what POSIX says about echo pubs.opengroup.org/onlinepubs/009604599/utilities/echo.htmlJudyjudye
@Gratulant No, it's not. -n prevents echo from writing a trailing newline, that's it. It has nothing to do with interrupting the digraph \n as a literal newline character: that's what -e is for.Samp
S
4147

Use printf instead:

printf "hello\nworld\n"

printf behaves more consistently across different environments than echo.

Signatory answered 11/12, 2011 at 21:4 Comment(19)
or even printf %"s\n" hello world -- printf will reuse the format if too many arguments are givenMatrilateral
The OP asked about echo, not printf; and @choroba's answer below, which uses the -e option, fills the bill perfectly.Zoubek
@JESii: It fits if your echo happens to support the -e option.Signatory
Fair enough, @sth. Then how about the echo $'xxx' approach.Zoubek
With some versions of echo, -e is just printed in the output itself so I think this answer is perfectly valid since echo isn't consistent here (unless we're talking about a specific version).Uda
This is well and good if printf is available, but unlike echo sometimes printf isn't on the distro.Dervish
@Dervish Then you can install it or reference the other answers. He said "You could use printf instead" and stated it's advantages.Hhour
@Dervish If you are using bash, which the asker specifies, then printf is a builtin command and comes with the shell (see man bash under "SHELL BUILTIN COMMANDS"). It's not distro-dependent in this case.Eakin
I can't seem to get printf "#\!/bin/bash > output.sh to work the way I would expect.Albany
@Dervish Even if the OP hadn't said they're using Bash and Ubuntu, the printf command has been standard for quite some time, and is also present as an executable, in case one's shell doesn't have it as a builtin. printf is regarded as the portable, reliable choice. You said "unlike echo sometimes printf isn't on the distro"--are there real examples of Unix-like (even if not generally POSIX-conforming) operating systems, that people actually use, that don't have a printf command?Conakry
I'm on WSL (Ubuntu 18.04) and I get this error: bash: printf: - : invalid option printf: usage: printf [-v var] format [arguments]Skewbald
Oh, for anyone else having the same issue with printf as mine try: printf "%b" "hello\nworld\n" Also to read more: wiki.bash-hackers.org/commands/builtin/printfSkewbald
@rustyx, that's true in C, not in bash. (Fixed format strings are good practice even in bash, yes; exploitable in the conventional way -- which is to say, on account of code making assumptions about location of variables on the stack and thus performing invalid reads -- not at all; the only issues that happen in bash are wrt. data that should be literal being instead treated as directives).Thole
@bigtunacan, printf is POSIX-specified in far more detail than echo is. That is to say, many different echo behaviors can call themselves POSIX-compliant, but every POSIX-compliant UNIX will have a printf command that behaves exactly the same way included (for all the standard-defined operators).Thole
I tried printf, but I end up with a trailing seemingly selected '%' sign. printf "abc" => ouputs abc% (running zsh on Debian GNU/Linux 10 (buster)) Thus falling back to the echo -e optionLair
@Lair Do you maybe miss a trailing \n and the % is your shell prompt?Signatory
@Signatory That indeed fixes the problem, but why then does the behavior change (no trailing %) when using bash or sh ? I am missing some piece information on zsh behavior ?Lair
@Wasabi: The % is not printed by printf, it's printed by zsh as part of its command prompt. Bash uses $ or something more complicated instead, that's why it looks different with bash. printf prints the same thing both times, and following that the shell prints it's command prompt. This command prompt looks different in zsh than in bash/sh.Signatory
@Signatory In this case, it's zsh printing a % to indicate that there was no trailing newline in the output, before unconditionally putting the prompt on the next line. (bash, by contrast, would simply print the prompt on the same line as the last of the output.) zsh's behavior is controlled by the PROMPT_SP and PROMPT_EOL_MARK options.Samp
T
2330

Make sure you are in Bash.

$ echo $0
bash

All these four ways work for me:

echo -e "Hello\nworld"
echo -e 'Hello\nworld'
echo Hello$'\n'world
echo Hello ; echo world
Transpacific answered 11/12, 2011 at 21:4 Comment(20)
-e flag did it for me, which "enables interpretation of backslash escapes"Elbowroom
I think -e param doesn't exist on all *nix OSTiemroth
@kenorb: It exists in bash. It is a builtin.Transpacific
Why does the third one work? Without the $ it returns "Hello n world"Rampart
One more way: echo -e hello\\nworldFulguration
As mentioned by various other -e does NOT work for all distributions and versions. In some cases it is ignored and in others it will actually be printed out. I don't believe this fixed it for the OP so should not be accepted answerHhour
@csga5000: the third option should work regardless of the version. Moreover, this isn't the accepted answer.Transpacific
@Transpacific Good point, the third option is a good solution. And I know it's not, I just was just countering the comment saying it should be accepted answer (which had 43 upvotes)Hhour
just type 'man echo' in the terminal and then it is clear that for enabling interpretation of backslash sequences we need to add '-e'; the documentation also provides all the common backslash sequences that can be interpreted.Bostwick
@Sheetalgupta: But help echo (in bash) shows a different page that describes the bash builtin.Transpacific
man bash and help echo show the same information for me ,rather man bash more detailed official documentationBostwick
man bash and help echo show the same information, but man echo doesn't.Transpacific
"Are you sure you're in bash?" It's the echo -e flag that makes this work as expected.Licko
@Christian: In other shells, the builtin echo doesn't have to support the -e flag. That's why I asked.Transpacific
@kenorb: except when 'echo' is not a builtin, but '/bin/echo'Proceleusmatic
At this point may I ask what the difference between echo -e and printf? Are there any performance penalties for using printf? Thanks in advance.Anthracoid
@ozanmuyes: echo -e might not be supported in other shells. echo doesn't understand the % placeholders that printf uses.Transpacific
@xamid Just know that the & makes a process go in background, so I would try echo Hello && echo world (the difference here is && instead of &)Nadeau
You are right, && is what I meant (& prints some undesired extra message about completion of the task). Plus echo Hello && echo world even works on Windows (where A && B means to execute B only when A executed successfully).Paugh
yea; another thing is ; if you simply don't care about the exit code(if the prev.commands was run s.fully or failed) it's shorter too, so yea, and have a nice day!Nadeau
N
753
echo $'hello\nworld'

prints

hello
world

$'' strings use ANSI C Quoting:

Character sequences of the form $’string are treated as a special kind of single quotes. The sequence expands to string, with backslash-escaped characters in string replaced as specified by the ANSI C standard.

Northwester answered 2/11, 2012 at 9:39 Comment(6)
@EvgeniSergeev Not sure what you mean, but it didn't work for me either first. And that's because I was using double quotes and turns out this works only with single quotes! Tried in Terminal on Mac.Ungotten
Problems with variables in the string not being expanded.Geostrophic
You can still concatenate double-quote strings. ` foo="bar"; echo $''$foo'efoot'`Ease
It woks on GNU bash, version 4.4.23(1)-release (x86_64-pc-msys) W10 like a charm.Malarkey
This also works for read -p prompt: read -p $'Quick!\n' -t 1Arrearage
PSA, not sh compatibleLambdacism
A
206

You could always do echo "".

For example,

echo "Hello,"
echo ""
echo "World!"
Adulteress answered 28/2, 2014 at 22:14 Comment(6)
echo "" works for me and I think it's the simplest form to print a new line, even if this doesn't directly answer the question. Cheers.Piquet
I think it's less obvious (and thus potentially more confusing) than echo -en "\n".Audrit
echo is enough to obtain an empty lineOboe
The \n did not work when you are using the read. But your method worked for adding a line.Bibliolatry
i had trouble getting the other answers to work on Mac. i ended up going with this incredibly obvious solution. :)Meditate
Doesn't this put 2 newlines between Hello and World ? Upvoted anyway because I value simplicity and clarity.Oulman
H
73

On the off chance that someone finds themselves beating their head against the wall trying to figure out why a coworker's script won't print newlines, look out for this:

#!/bin/bash
function GET_RECORDS()
{
   echo -e "starting\n the process";
}

echo $(GET_RECORDS);

As in the above, the actual running of the method may itself be wrapped in an echo which supersedes any echos that may be in the method itself. Obviously, I watered this down for brevity. It was not so easy to spot!

You can then inform your comrades that a better way to execute functions would be like so:

#!/bin/bash
function GET_RECORDS()
{
   echo -e "starting\n the process";
}

GET_RECORDS;
Harrod answered 8/8, 2013 at 20:15 Comment(1)
Be sure you wrap the variable with quotes before echoing it out of the method.Pisciculture
B
42

Simply type

echo

to get a new line

Belldas answered 1/6, 2019 at 16:13 Comment(6)
Vastly underrated answer, can't believe this question has amassed 20+ answers since 2011 and that not one of them contains this simple solution.Soilure
@Ahi Tuna: Please use your console keyboard shortcuts instead :)Belldas
@RSun and how would I do that on a Debian terminal window on a Chromebook?Venavenable
@AhiTuna printf "\033c"Othilia
On the screen-clearing, Ctrl+L will also clear the screen on the majority of terminals.Nawrocki
@AhiTuna to clear screen, just type clear commandUnjaundiced
T
37

For only the question asked (not special characters etc) changing only double quotes to single quotes.

echo -e 'Hello,\nWorld!'

Results in:

Hello,
World!
Tuberose answered 10/6, 2022 at 17:19 Comment(1)
Tested with double quotes in RHEL 9.7 and works fine.Disheveled
B
34

POSIX 7 on echo

http://pubs.opengroup.org/onlinepubs/9699919799/utilities/echo.html

-e is not defined and backslashes are implementation defined:

If the first operand is -n, or if any of the operands contain a <backslash> character, the results are implementation-defined.

unless you have an optional XSI extension.

So I recommend that you should use printf instead, which is well specified:

format operand shall be used as the format string described in XBD File Format Notation [...]

the File Format Notation:

\n <newline> Move the printing position to the start of the next line.

Also keep in mind that Ubuntu 15.10 and most distros implement echo both as:

  • a Bash built-in: help echo
  • a standalone executable: which echo

which can lead to some confusion.

Best answered 22/1, 2016 at 13:23 Comment(0)
P
22
str='hello\nworld'
$ echo | sed "i$str"
hello
world
Physostomous answered 23/11, 2012 at 11:10 Comment(2)
This is actually a great answer since it works for string concatenations. Great!Oletaoletha
Why bother to invoke a second program? It's not that we are trying to write a real time application in bash ;) but its not necessary.Luella
K
16

You can also do:

echo "hello
world"

This works both inside a script and from the command line.

On the command line, press Shift+Enter to do the line break inside the string.

This works for me on my macOS and my Ubuntu 18.04 (Bionic Beaver) system.

Keim answered 31/8, 2018 at 7:40 Comment(0)
H
12

There is a new parameter expansion added in Bash 4.4 that interprets escape sequences:

${parameter@operator} - E operator

The expansion is a string that is the value of parameter with backslash escape sequences expanded as with the $'…' quoting mechanism.

$ foo='hello\nworld'
$ echo "${foo@E}"
hello
world
Hygroscope answered 23/7, 2018 at 19:54 Comment(1)
worked like a charm for printing a message that was a variable inside a function, from outside the function.Redness
E
10

I just use echo without any arguments:

echo "Hello"
echo
echo "World"
Elvieelvin answered 13/3, 2020 at 17:50 Comment(1)
This is wrong as Hello is followed by two line breaks and not only one.Frannie
C
9

To print a new line with echo, use:

echo

or

echo -e '\n'
Cowper answered 24/1, 2022 at 15:44 Comment(0)
B
6

My script:

echo "WARNINGS: $warningsFound WARNINGS FOUND:\n$warningStrings

Output:

WARNING : 2 WARNINGS FOUND:\nWarning, found the following local orphaned signature file:

On my Bash script I was getting mad as you until I've just tried:

echo "WARNING : $warningsFound WARNINGS FOUND:
$warningStrings"

Just hit Enter where you want to insert that jump. The output now is:

WARNING : 2 WARNINGS FOUND:
Warning, found the following local orphaned signature file:
Breakdown answered 14/5, 2014 at 8:58 Comment(3)
Just a note, you will probably want to use ${ } around your variable names as not doing so can lead to really weird behavior when a shell finds a variable called $warningsFound and prints that and not the two separate outputs.Syd
@Syd maybe I'm missing something, but the variable IS actually called $warningsFound ?Stiff
I missed a word on that. If you had a variable called $warnings, in some cases without using ${warningsFound}, you could potentially end up with the contents of $warnings + "Found" instead of the variable you intended.Syd
S
6

This could better be done as

x="\n"
echo -ne $x

-e option will interpret backslahes for the escape sequence
-n option will remove the trailing newline in the output

PS: the command echo has an effect of always including a trailing newline in the output so -n is required to turn that thing off (and make it less confusing)

Steeplejack answered 30/5, 2017 at 7:0 Comment(1)
echo -ne "hello\nworld" for the exact answer of the question :)Steeplejack
K
6

If you're writing scripts and will be echoing newlines as part of other messages several times, a nice cross-platform solution is to put a literal newline in a variable like so:

newline='
'

echo "first line${newline}second line"
echo "Error: example error message n${newline}${usage}" >&2 #requires usage to be defined
Khosrow answered 1/7, 2019 at 20:6 Comment(0)
L
5

If the previous answers don't work, and there is a need to get a return value from their function:

function foo()
{
    local v="Dimi";
    local s="";
    .....
    s+="Some message here $v $1\n"
    .....
    echo $s
}

r=$(foo "my message");
echo -e $r;

Only this trick worked on a Linux system I was working on with this Bash version:

GNU bash, version 2.2.25(1)-release (x86_64-redhat-linux-gnu)
Lignify answered 31/1, 2014 at 14:20 Comment(0)
R
4

In a .command file in MacOS, the following works;

  • echo $'\nAll \nis \ndone!'

  • echo -e $"\nAll \nis \ndone!"

  • echo $'\n'

Retraction answered 3/10, 2023 at 12:52 Comment(0)
T
3

You could also use echo with braces,

$ (echo hello; echo world)
hello
world
Towhee answered 5/5, 2014 at 9:32 Comment(4)
syntax error near unexpected token `(' when called in .sh fileKarleen
try echo hello; echo worldTowhee
Or "echo hello && echo world" or just:" echo hello echo worldHhour
An explanation would be in order.Enfield
M
2

This got me there....

outstuff=RESOURCE_GROUP=[$RESOURCE_GROUP]\\nAKS_CLUSTER_NAME=[$AKS_CLUSTER_NAME]\\nREGION_NAME=[$REGION_NAME]\\nVERSION=[$VERSION]\\nSUBNET-ID=[$SUBNET_ID]
printf $outstuff

Yields:

RESOURCE_GROUP=[akswork-rg]
AKS_CLUSTER_NAME=[aksworkshop-804]
REGION_NAME=[eastus]
VERSION=[1.16.7]
SUBNET-ID=[/subscriptions/{subidhere}/resourceGroups/makeakswork-rg/providers/Microsoft.Network/virtualNetworks/aks-vnet/subnets/aks-subnet]
Maris answered 11/5, 2020 at 14:52 Comment(2)
An explanation would be in order. E.g, what is the gist/idea? Please respond by editing your answer, not here in comments (without "Edit:", "Update:", or similar - the answer should appear as if it was written today).Enfield
This is a good use when you can't add quotes!Quincyquindecagon
A
1

Sometimes you can pass multiple strings separated by a space and it will be interpreted as \n.

For example when using a shell script for multi-line notifcations:

#!/bin/bash
notify-send 'notification success' 'another line' 'time now '`date +"%s"`
Ajar answered 26/5, 2018 at 7:14 Comment(1)
This is incorrect. It is never interpreted as \n. It is interpreted as a separate argument to the program, and the program itself may display that argument on a new line, but that doesn't mean that it was converted to \n at any point and is entirely dependent on the program.Hexapartite
A
1

I would like to add that when you try to echo lines after running a process in the background, like some_script &, you lost the implicit \r (carriage return) in a new line so the output of:

some_script &
echo "firsf"
echo "second"

could be something like:

fist
    second

There is a line break, but not a "carriage return", to fix this, we could add \r:

echo -e 'fist\r'
echo -e 'second\r'
Agra answered 5/9, 2023 at 17:39 Comment(0)
H
-2

You can just use PHP_EOL

echo "Hello" . PHP_EOL . "World";

result in console :

Hello
World
Haileyhailfellowwellmet answered 6/3 at 10:25 Comment(0)
S
-5

Additional solution:

In cases, you have to echo a multiline of the long contents (such as code/ configurations)

For example:

  • A Bash script to generate codes/ configurations

echo -e, printf might have some limitation

You can use some special char as a placeholder as a line break (such as ~) and replace it after the file was created using tr:

echo ${content} | tr '~' '\n' > $targetFile

It needs to invoke another program (tr) which should be fine, IMO.

Shelter answered 10/5, 2019 at 3:7 Comment(1)
This is a poor solution. There is absolutely no need to invoke tr in this case. Furthermore, what if the text includes a ~ already?Kilan
K
-5

With jq:

$ jq -nr '"Hello,\nWorld"'
Hello,
World
Keratoplasty answered 14/6, 2022 at 18:39 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.