This question already has an answer here:
- How can I have a newline in a string in sh? 10 answers
I have
var="a b c"
for i in $var
do
p=`echo -e $p'\n'$i`
done
echo $p
I want last echo to print
a
b
c
Notice that I want the variable p to contain newlines. How do I do that?
The solution was simply to protect the inserted newline with a "" during current iteration when variable substitution happens.
Try
echo $'a\nb'
.If you want to store it in a variable and then use it with the newlines intact, you will have to quote your usage correctly:
Or, to fix your example program literally:
Summary
Inserting
\n
Inserting a new line in the source code
Using
$'\n'
(only bash and zsh)Details
1. Inserting
\n
echo -e
interprets the two characters"\n"
as a new line.Avoid extra leading newline
Using a function
2. Inserting a new line in the source code
Avoid extra leading newline
Using a function
3. Using
$'\n'
(less portable)bash and zsh interprets
$'\n'
as a new line.Avoid extra leading newline
Using a function
Output is the same for all
Special thanks to contributors of this answer: kevinf, Gordon Davisson, l0b0, Dolda2000 and tripleee.
EDIT
for
loop in above bash snippets.sed
solution:Result:
The trivial solution is to put those newlines where you want them.
Yes, that's an assignment wrapped over multiple lines.
However, you will need to double-quote the value when interpolating it, otherwise the shell will split it on whitespace, effectively turning each newline into a single space (and also expand any wildcards).
Generally, you should double-quote all variable interpolations unless you specifically desire the behavior described above.
There are three levels at which a newline could be inserted in a variable.
Well ..., technically four, but the first two are just two ways to write the newline in code.
1.1. At creation.
The most basic is to create the variable with the newlines already.
We write the variable value in code with the newlines already inserted.
Or, inside an script code:
Yes, that means writing Enter where needed in the code.
1.2. Create using shell quoting.
The sequence $' is an special shell expansion in bash and zsh.
The line is parsed by the shell and expanded to « var="anewlinebnewlinec" », which is exactly what we want the variable var to be.
That will not work on older shells.
2. Using shell expansions.
It is basically a command expansion with several commands:
echo -e
The bash and zsh printf '%b'
The bash printf -v
Plain simple printf (works on most shells):
3. Using shell execution.
All the commands listed in the second option could be used to expand the value of a var, if that var contains special characters.
So, all we need to do is get those values inside the var and execute some command to show:
Note that printf is somewhat unsafe if var value is controlled by an attacker.