Bash string with newline


This post goes over how to include newlines in a Bash string.

Problem

If you’re using Bash:

echo $0 # bash

You may notice that newline characters are escaped in strings:

echo "hello\nworld" # hello\nworld

Solution

echo

To preserve the newline in echo, you can set option -e:

echo -e 'hello\nworld'
hello
world

variable

Alternatively, you can assign the newline character to a variable:

NL=$'\n'

And then substitute it via parameter expansion:

echo "hello${NL}world"
hello
world

Make sure to use double quotes "..." otherwise the variable reference won’t be expanded.



Please support this site and join our Discord!