2791

In Bash, tried this:

echo -e "Hello,\nWorld!"

But it doesn't print a newline, only \n. How can I make it print the newline?

I'm using Ubuntu 11.04 (Natty Narwhal).

Peter Mortensen
  • 28,342
  • 21
  • 95
  • 123
Sergey
  • 39,828
  • 24
  • 80
  • 122
  • 295
    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). – Gordon Davisson Dec 12 '11 at 01:58
  • 8
    Also notable: in Unix & Linux Stack Exchange, the [accepted answer](http://unix.stackexchange.com/a/219274/13260) to *How to add new lines when using echo* – Graham Perrin Apr 09 '16 at 07:02
  • 6
    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: *https://stackoverflow.com/questions/27872069/how-to-debug-a-bash-function-that-returns-a-value-and-how-to-add-newlines-to-a/27872114* This was like a three hour mystery tour. – aliteralmind Jan 10 '15 at 03:28
  • 2
    echo -ne "hello\nworld" (you needed the n flag to interpret escapes) - but as others say, different echo commands may have different results! – Konchog Mar 28 '18 at 07:00
  • @Konchog `echo -n` man page entry on archlinux ` -n do not output the trailing newline` It has nothing to do with interpreting escapes –  May 27 '20 at 18:19
  • @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. – Konchog May 28 '20 at 08:13
  • It works fine in Bash corresponding to [Ubuntu MATE 20.04](https://en.wikipedia.org/wiki/Ubuntu_MATE#Releases) (Focal Fossa) - Bash version 5.0.17 (`GNU bash, version 5.0.17(1)-release (x86_64-pc-linux-gnu)`) – Peter Mortensen Apr 19 '21 at 19:25

23 Answers23

3371

You could use printf instead:

printf "hello\nworld\n"

printf has more consistent behavior than echo. The behavior of echo varies greatly between different versions.

sth
  • 200,334
  • 49
  • 262
  • 354
  • 54
    or even `printf %"s\n" hello world` -- printf will reuse the format if too many arguments are given – glenn jackman Dec 12 '11 at 00:57
  • 37
    The OP asked about echo, not printf; and @choroba's answer below, which uses the -e option, fills the bill perfectly. – JESii May 27 '15 at 13:46
  • 67
    @JESii: It fits if your `echo` happens to support the `-e` option. – sth May 27 '15 at 13:57
  • 1
    Fair enough, @sth. Then how about the echo $'xxx' approach. – JESii May 29 '15 at 23:28
  • 14
    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). – Tejas Manohar Jun 10 '15 at 19:47
  • 17
    This is well and good if printf is available, but unlike echo sometimes printf isn't on the distro. – bigtunacan Aug 18 '15 at 13:53
  • 2
    @bigtunacan Then you can install it or reference the other answers. He said "You could use printf instead" and stated it's advantages. – csga5000 Apr 15 '16 at 04:19
  • 12
    @bigtunacan 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. – user2221343 Oct 20 '16 at 12:47
  • I can't seem to get `printf "#\!/bin/bash > output.sh` to work the way I would expect. – anon58192932 May 04 '17 at 17:18
  • 10
    @bigtunacan Even if the OP hadn't said they're using Bash and Ubuntu, [the `printf` command has been standard for quite some time](http://pubs.opengroup.org/onlinepubs/7908799/xcu/printf.html), 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.](https://unix.stackexchange.com/q/65803) 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? – Eliah Kagan Jul 05 '17 at 03:21
  • 1
    I'm on WSL (Ubuntu 18.04) and I get this error: bash: printf: - : invalid option printf: usage: printf [-v var] format [arguments] – aderchox Feb 05 '19 at 08:29
  • Oh, for anyone else having the same issue with printf as mine try: `printf "%b" "hello\nworld\n"` Also to read more: https://wiki.bash-hackers.org/commands/builtin/printf – aderchox Feb 05 '19 at 08:42
  • @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). – Charles Duffy Jul 17 '19 at 22:19
  • 2
    @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). – Charles Duffy Dec 08 '19 at 03:19
  • @rustyx, that's true in C. It's not true in bash; its `printf` implementation is entirely independent of the C one. – Charles Duffy Dec 08 '19 at 03:21
1948

Make sure you are in Bash. All these four ways work for me:

echo -e "Hello\nworld"
echo -e 'Hello\nworld'
echo Hello$'\n'world
echo Hello ; echo world
Peter Mortensen
  • 28,342
  • 21
  • 95
  • 123
choroba
  • 200,498
  • 20
  • 180
  • 248
  • 421
    -e flag did it for me, which "enables interpretation of backslash escapes" – tandy Aug 07 '13 at 20:52
  • 25
    I think ```-e``` param doesn't exist on all *nix OS – kenorb Sep 04 '13 at 15:28
  • 14
    @kenorb: It exists in bash. It is a builtin. – choroba Sep 04 '13 at 20:09
  • 1
    Why does the third one work? Without the $ it returns "Hello n world" – Evan Donovan Nov 11 '13 at 21:33
  • One more way: `echo -e hello\\nworld` – BartekChom Aug 26 '15 at 08:16
  • 28
    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 answer – csga5000 Apr 15 '16 at 04:23
  • @csga5000: the third option should work regardless of the version. Moreover, this isn't the accepted answer. – choroba Apr 15 '16 at 05:32
  • @choroba 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) – csga5000 Apr 15 '16 at 22:46
  • 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. – Sheetal gupta Feb 21 '19 at 09:31
  • @Sheetalgupta: But `help echo` (in bash) shows a different page that describes the bash builtin. – choroba Feb 21 '19 at 12:27
  • **man bash** and **help echo** show the same information for me ,rather **man bash** more detailed official documentation – Sheetal gupta Feb 21 '19 at 15:36
  • man bash and help echo show the same information, but `man echo` doesn't. – choroba Feb 21 '19 at 16:33
  • "Are you sure you're in bash?" It's the `echo -e` flag that makes this work as expected. – C. Lewis Jan 14 '20 at 00:24
  • @Christian: In other shells, the builtin `echo` doesn't have to support the `-e` flag. That's why I asked. – choroba Jan 14 '20 at 08:06
638
echo $'hello\nworld'

prints

hello
world

$'' strings use ANSI C Quoting:

Words of the form $'string' are treated specially. The word expands to string, with backslash-escaped characters replaced as specified by the ANSI C standard.

Rory O'Kane
  • 25,436
  • 11
  • 86
  • 123
Vanuan
  • 25,939
  • 9
  • 90
  • 96
160

You could always do echo "".

For example,

echo "Hello,"
echo ""
echo "World!"
Peter Mortensen
  • 28,342
  • 21
  • 95
  • 123
Nayeem Zen
  • 2,136
  • 1
  • 15
  • 16
85

Try

echo -e "hello\nworld"
hello
world

worked for me in nano editor.

From the man page:

-e enable interpretation of backslash escapes

Harsha Biyani
  • 5,322
  • 7
  • 32
  • 48
47

In 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;
Uncle Iroh
  • 4,961
  • 4
  • 43
  • 55
30

Simply type

echo

to get a new line

vinzee
  • 10,965
  • 9
  • 34
  • 51
R Sun
  • 871
  • 10
  • 13
  • 3
    Vastly underrated answer, can't believe this question has amassed 20+ answers since 2011 and that not one of them contains this simple solution. – Hashim Aziz Dec 04 '19 at 17:37
  • 2
    alias c='echo ; echo ; echo ; echo ; echo ; echo ; echo ; echo ; echo ; echo ; echo ; echo ; echo ; echo ; echo ; echo ; echo ; echo ; echo ; echo ; echo ; echo ; echo ; echo ; echo ; echo ; echo ; echo ; echo ; echo ; echo ; echo ; echo ; echo ; echo ; echo ;' This is the only way I can clear my screen, thanks! – Ahi Tuna Dec 09 '19 at 14:38
  • @Ahi Tuna: Please use your console keyboard shortcuts instead :) – R Sun Dec 09 '19 at 18:17
  • @RSun and how would I do that on a Debian terminal window on a Chromebook? – Ahi Tuna Dec 11 '19 at 12:07
  • @AhiTuna printf "\033c" – Aquadarius May 26 '20 at 08:22
  • On the screen-clearing, Ctrl+L will also clear the screen on the majority of terminals. – Soren Bjornstad Jun 30 '20 at 02:39
  • 4
    @AhiTuna to clear screen, just type `clear` command – Yongfeng Dec 16 '20 at 05:40
27

This works for me in Raspbian,

echo -e "hello\\nworld"
Peter Mortensen
  • 28,342
  • 21
  • 95
  • 123
Sathesh
  • 5,846
  • 6
  • 33
  • 44
27

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.

16
str='hello\nworld'
$ echo | sed "i$str"
hello
world
alinsoar
  • 13,197
  • 4
  • 45
  • 63
9

You can also do:

echo "hello
world"

This works both inside a script and from the command line.
In 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

vinzee
  • 10,965
  • 9
  • 34
  • 51
  • @Xenos This works well in a script. And in the console, just click on Shift + Enter to add a new line to avoid having the shell to run the unfinished command. – vinzee Aug 07 '19 at 17:28
8

It works for me in CentOS:

echo -e ""hello\nworld""
vanishedzhou
  • 169
  • 2
  • 4
6

I just use echo no arguments

echo "Hello"
echo
echo "World"
Xenon
  • 109
  • 1
  • 6
4

One more entry here for those that didn't make it work with any of these solutions, and 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)
Peter Mortensen
  • 28,342
  • 21
  • 95
  • 123
DNT
  • 2,196
  • 12
  • 15
4

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. Output now is:

WARNING : 2 WARNINGS FOUND:
Warning, found the following local orphaned signature file:
TanisDLJ
  • 897
  • 11
  • 16
  • 6
    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. – dragon788 Jan 27 '16 at 21:06
  • @dragon788 maybe I'm missing something, but the variable IS actually called $warningsFound ? – psynnott Feb 10 '17 at 09:47
  • 3
    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. – dragon788 Feb 10 '17 at 13:12
4

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)

Dhwanit
  • 543
  • 6
  • 16
4

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
PesaThe
  • 6,628
  • 1
  • 13
  • 37
4

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$newlinesecond line"
echo "Error: example error message n${newline}${usage}" >&2 #requires usage to be defined
skiggety
  • 170
  • 6
3

You could also use echo with braces,

$ (echo hello; echo world)
hello
world
Avinash Raj
  • 160,498
  • 22
  • 182
  • 229
1

This may not apply in your case, but it's something that has confused me in the past:

Wrong

Writing "hello\nworld" in Bash gives you a string with a new-line character in it, and echo -e prints that exact string.

Right

Writing $'hello\nworld' or

"hello
world"

gives you a string with a new-line character in it, and plain echo prints that exact string. Which is good, since as you've seen, echo -e isn't always supported.

JW.
  • 47,690
  • 30
  • 108
  • 133
0

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"`
Hunter Frazier
  • 447
  • 5
  • 9
  • 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. – Score_Under Mar 27 '19 at 10:52
0

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]
Joe Healy
  • 5,349
  • 3
  • 32
  • 54
-4

Additional solution :

In cases, You have to echo 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 need to invoke another program (tr) which should be fine IMO.

ZenithS
  • 824
  • 6
  • 17
  • This is a poor solution. There is absolutely no need to invoke `tr` in this case. Furthermore, what if the text includes a `~` already? – blackbrandt Jul 22 '20 at 15:14