Losing newline after assigning grep result to a shell variable

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)

Leave a Comment