Adding newline characters to unix shell variables

Other than $'\n' you can use printf also like this:

VARIABLE="Foo Bar"
VARIABLE=$(printf "${VARIABLE}\nSomeData")
echo "$VARIABLE"

OUTPUT:

Foo Bar
SomeData

A common technique is:

nl='
'
VARIABLE="PreviousData"
VARIABLE="$VARIABLE${nl}SomeData"

echo "$VARIABLE"
PreviousData
SomeData

Also common, to prevent inadvertently having your string start with a newline:

VARIABLE="$VARIABLE${VARIABLE:+$nl}SomeData"

(The expression ${VARIABLE:+$nl} will expand to a newline if and only if VARIABLE is set and non-empty.)


VAR="one"
VAR="$VAR.\n.two"
echo -e $VAR

Output:

one.
.two


Try $'\n':

VAR=a
VAR="$VAR"$'\n'b
echo "$VAR"

gives me

a
b