6

I have the following bash string and I need to add a line break to it, before the 'Hello' string:

bash -c "echo 'Hello' > /location/file"

I already tried adding it with different variations of the \n syntax; Before the double quotes, inside the range of the double quotes, and with different variations of escaping.

How could I add a line break just before the 'Hello' string, so to make it appear in the second row?

Gilles 'SO- stop being evil'
  • 807,993
  • 194
  • 1,674
  • 2,175

3 Answers3

9

There are (at least) three options here.

  1. Use a literal newline:
bash -c "echo '
Hello' > /location/file"
  1. Use printf (or the non-standard echo -e), which expands backslash escaped characters as part of the commands themselves (of which both are shell builtins):
bash -c "printf '\n%s\n' Hello > /location/file"
  1. Use bash's nonstandard $' quoting, which expands backslash escaped characters as part of the shell:
bash -c "echo $'\nHello' > /location/file
Chris Down
  • 122,090
  • 24
  • 265
  • 262
  • There are three options, and the third one (which I am amazed to see not mentioned in any answer here since it is an exceedingly common answer to the problem of `echo` and backslash, given several times over on this very WWW site alone) _is_ standard. – JdeBP Jan 03 '17 at 09:23
  • 1
    @JdeBP: What would that 3rd method be? `printf`, literal newlines within a quoted string? – Gert van den Berg Jan 04 '17 at 12:41
7

You may use $'\n':

$ bash -c "echo $'\nHello'" >somefile

The Bash manual mentions this:

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. Backslash escape sequences, if present, are decoded as follows:

(table of standard escape sequences left out)

Kusalananda
  • 320,670
  • 36
  • 633
  • 936
1

You can do it with:

bash -c "echo $'\nHello'"
Zumo de Vidrio
  • 1,703
  • 1
  • 13
  • 28