Home » Linux » Adding newline characters to unix shell variables

Adding newline characters to unix shell variables

Posted by: admin November 29, 2017 Leave a comment

Questions:

I am new to shell scripting. I have a variable in a shell script in which I’d like to format the data. The variable stores new data during every iteration of a loop. Each time the new data is stored, I’d like to insert a new line character. Here is how I’m trying to store the data into the variable.

VARIABLE="$VARIABLE '\n' SomeData"

Unfortunately, the output includes the literal '\n' Any help would be appreciative. Thanks in advance.

Answers:

Try $'\n':

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

gives me

a
b

Questions:
Answers:

A common technique is:

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

echo "$VARIABLE"
PreviousData
SomeData

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

Output:

one.

.two

Questions:
Answers:

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

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

OUTPUT:

Foo Bar
SomeData

Questions:
Answers:

I had a problem with all the other solutions: when using a # followed by SPACE (quite common when writing in Markdown) both would get split onto a new line.

So, another way of doing it would involve using single quotes so that the “\n” get rendered.

FOO=$'# Markdown Title #\n'
BAR=$'Be *brave* and **bold**.'
FOOBAR="$FOO$BAR"

echo "$FOOBAR"

Output:

# Markdown Title #
Be *brave* and **bold**.

Questions:
Answers:

Single quote All special characters between these quotes lose their
special meaning.
https://www.tutorialspoint.com/unix/unix-quoting-mechanisms.htm

So the syntax you use does something different that you want to achieve.

This is what you need:

The $’\X’ construct makes the -e option in echo unnecessary.

https://linux.die.net/abs-guide/escapingsection.html

echo -e "something\nsomething"

or

echo "something"$'\n'"something"

Questions:
Answers:

It’s a lot simpler than you think:

VARIABLE="$VARIABLE
SomeData"