Newline loss after assigning grep result to shell variable

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

Normally, grep displays each match on its own line at startup on the command line. However, in the above scenarios, the new line separating each match disappears. Does anyone know how to save a new line?

+51
shell
Apr 16 '09 at 0:59
source share
3 answers

You do not lose it in the task, but in the echo. You can see this clearly if:

 echo "${out}" 

You will 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, not relevant to your question, but I would like to mention this, I prefer to use the $ () construct rather than backlinks, just to be able to use the commands. So your script line will look like this:

 out=$(grep apache README) 

Now it may look different (and it’s not), but it makes more complex commands like:

 lines_with_nine=$(grep $(expr 7 + 2) inputfile) 
+69
Apr 16 '09 at 1:08
source share

Put $ out in quotes:

 #!/usr/local/bin/bash out=`grep apache README` echo "$out"; 
+23
Apr 16 '09 at 1:05
source share

Quoting variables in bash preserves spaces.

For example:

 #!/bin/bash var1="ABCD" echo $var1 # ABCD echo "$var1" # ABCD 

since newlines are spaces that they β€œremove”

+11
Apr 16 '09 at 2:15
source share



All Articles