Losing newline after assigning grep result to a shell variable

Shell

Shell Problem Overview


#!/usr/local/bin/bash
out=`grep apache README`
echo $out;

Usually grep shows each match on a separate line when run on the command line. However, in the above scripts, the newline separating each match disappears. Does anyone know how the newline can be preserved?

Shell Solutions


Solution 1 - Shell

You're not losing it in the assignment but in the echo. You can see this clearly if you:

echo "${out}"

You'll see a similar effect with the following script:

x="Hello,
I
am
a
string
with
newlines"
echo "====="
echo ${x}
echo "====="
echo "${x}"
echo "====="

which outputs:

=====
Hello, I am a string with newlines
=====
Hello,
I
am
a
string
with
newlines
=====

And, irrelevant to your question but I'd like to mention it anyway, I prefer to use the $() construct rather than backticks, just for the added benefit of being able to nest commands. So your script line becomes:

out=$(grep apache README)

Now that may not look any different (and it isn't) but it makes possible more complex commands like:

lines_with_nine=$(grep $(expr 7 + 2) inputfile)

Solution 2 - Shell

Put $out in quotes:

#!/usr/local/bin/bash
out=`grep apache README`
echo "$out";

Solution 3 - Shell

Quoting variables in bash preserves the whitespace.

For instance:

#!/bin/bash
var1="A B  C   D"
echo $var1   # A B C D
echo "$var1" # A B  C   D

since newlines are whitespace they get "removed"

Solution 4 - Shell

Combining other answers into a one liner:

echo "($(grep apache README))"

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionLakshmirView Question on Stackoverflow
Solution 1 - ShellpaxdiabloView Answer on Stackoverflow
Solution 2 - ShellPestoView Answer on Stackoverflow
Solution 3 - ShellTanjView Answer on Stackoverflow
Solution 4 - ShellparagbaxiView Answer on Stackoverflow