-5

Whenever im trying to insert output with a line break into a variable for instance like this:

Hello
World

Once i do an echo command on the variable i get this: "Hello World"

Why does it happen and how can i keep the line break?

  • 1
    What language? Is this `bash`? – abligh Dec 17 '14 at 23:53
  • 3
    Quotes: They're important. `echo $var` **does not** show you the literal and unmodified contents of `var`. `echo "$var"` will _mostly_ do so, but if you want something that covers the corner cases, you're better off with `printf '%s\n' "$var"` -- or, to display unprintable characters in a readable form, `printf '%q\n' "$var"`. – Charles Duffy Dec 18 '14 at 00:00
  • 2
    so, moral of this story: Don't trust `echo` to faithfully tell you what you're storing in your variables, and _especially_ don't trust it without proper quoting. Assuming that the problem is with the storage and not with the printing is half the problem. – Charles Duffy Dec 18 '14 at 00:02
  • 2
    That said -- failing to show a demonstration of how you're getting content with linebreaks _into_ the variable makes this a poor question. – Charles Duffy Dec 18 '14 at 00:03

2 Answers2

3

In bash, the easiest way to express a literal line break is with $'' syntax:

var=$'Hello\nWorld'
echo "$var"

Note that the quotes around $var are mandatory during expansion if you want to preserve linebreaks or other whitespace! If you only run

echo $var

...then even though a linebreak is stored in your variable, you will see

Hello World

on a single line, as opposed to

Hello
World

on two lines.


This happens because when you don't use quotes, the shell splits the expanded words on whitespace -- including newlines -- and passes each item created by that split as a separate argument. Thus,

echo "$var"

will pass a single string with the entire expansion of $var, whereas

echo $var

will run the equivalent of:

echo "Hello" "World"

...passing each word in the text as a separate argument to echo (whereafter the echo command re-joins its arguments by spaces, resulting in the behavior described).

Charles Duffy
  • 280,126
  • 43
  • 390
  • 441
  • Well explained answer, thank you very much my friend:) – The AmsterO Dec 18 '14 at 00:07
  • It would be more correct to explain that word break is performed on `IFS`. Because, e.g.,: `IFS= var=$'Hello\nWorld'; echo $var` would properly output the newline. Yet, there's another problem when not using quotes: pathname expansion. – gniourf_gniourf Dec 18 '14 at 09:45
0

Line breaks can be embedded in a string in any POSIX compatible shell:

$ str="Hello
> World"
$ echo "$str"
Hello
World

If you hit enter before closing the quotation marks, the shell knows you have not yet finished the quoted material, and prints the secondary prompt (>) and waits for you to finish the command.

chepner
  • 497,756
  • 71
  • 530
  • 681