[bash 3.2.57(1) on OSX 10.11.6]
I am mysteriously losing concluding blank lines in a variable to which I have assigned the output of a command that ends in several blank lines.
[1] $ p="next line is blank
next several lines are blank
"
[2] $ echo $p
next line is blank next several lines are blank
[3] $ echo "$p"
next line is blank
next several lines are blank
[4] $ q="$p"
[5] $ echo "$q"
next line is blank
next several lines are blank
[6] $ r=`echo "$p"`
[7] $ echo "$r"
next line is blank
next several lines are blank
[8] $
Everything that happens in [1] through [6] is as expected.
But [7] is bewildering. Where did the final lines go, and what can I do to keep them when I set r
to the result of executing a command? (My real command does much more than just echo, but echo is a good minimal example.) Why does this work when I use the value of a variable but not the output of a command?
this is actually expected behavior.
check here http://www.gnu.org/software/bash/manual/html_node/Command-Substitution.html
Note what it say here
Bash performs the expansion by executing command in a subshell environment and replacing the command substitution with the standard output of the command, with any trailing newlines deleted.
to resolve it yu can do this trick (we add one letter at the end of the string so we preserve the lines before it then we remove it)
r=`echo "$p"n`
rr=${r::-1}
echo "$rr"