Issue
I have
var="a b c"
for i in $var
do
p=`echo -e $p'\n'$i`
done
echo $p
I want the last echo to print:
a
b
c
Notice that I want the variable p to contain newlines. How do I do that?
Solution
Summary
Inserting a new line in the source code
p="${var1} ${var2}" echo "${p}"
Using
$'\n'
(only Bash and Z shell)p="${var1}"$'\n'"${var2}" echo "${p}"
Using
echo -e
to convert\n
to a new linep="${var1}\n${var2}" echo -e "${p}"
Details
Inserting a new line in the source code
var="a b c" for i in $var do p="$p $i" # New line directly in the source code done echo "$p" # Double quotes required # But -e not required
Avoid extra leading newline
var="a b c" first_loop=1 for i in $var do (( $first_loop )) && # "((...))" is Bash specific p="$i" || # First -> Set p="$p $i" # After -> Append unset first_loop done echo "$p" # No need -e
Using a function
embed_newline() { local p="$1" shift for i in "$@" do p="$p $i" # Append done echo "$p" # No need -e } var="a b c" p=$( embed_newline $var ) # Do not use double quotes "$var" echo "$p"
Using
$'\n'
(less portable)bash and zsh interprets
$'\n'
as a new line.var="a b c" for i in $var do p="$p"$'\n'"$i" done echo "$p" # Double quotes required # But -e not required
Avoid extra leading newline
var="a b c" first_loop=1 for i in $var do (( $first_loop )) && # "((...))" is bash specific p="$i" || # First -> Set p="$p"$'\n'"$i" # After -> Append unset first_loop done echo "$p" # No need -e
Using a function
embed_newline() { local p="$1" shift for i in "$@" do p="$p"$'\n'"$i" # Append done echo "$p" # No need -e } var="a b c" p=$( embed_newline $var ) # Do not use double quotes "$var" echo "$p"
Using
echo -e
to convert\n
to a new linep="${var1}\n${var2}" echo -e "${p}"
echo -e
interprets the two characters"\n"
as a new line.var="a b c" first_loop=true for i in $var do p="$p\n$i" # Append unset first_loop done echo -e "$p" # Use -e
Avoid extra leading newline
var="a b c" first_loop=1 for i in $var do (( $first_loop )) && # "((...))" is bash specific p="$i" || # First -> Set p="$p\n$i" # After -> Append unset first_loop done echo -e "$p" # Use -e
Using a function
embed_newline() { local p="$1" shift for i in "$@" do p="$p\n$i" # Append done echo -e "$p" # Use -e } var="a b c" p=$( embed_newline $var ) # Do not use double quotes "$var" echo "$p"
⚠ Inserting
"\n"
in a string is not enough to insert a new line:"\n"
are just two characters.
The output is the same for all
a
b
c
Special thanks to contributors of this answer: kevinf, Gordon Davisson, l0b0, Dolda2000 and tripleee.
- See also BinaryZebra's answer, providing many details.
- Abhijeet Rastogi's answer and Dimitry's answer explain how to avoid the
for
loop in the above Bash snippets.
Answered By - oHo Answer Checked By - Clifford M. (WPSolving Volunteer)