Bash – Why there isn’t a new line at the end of quoting a subshell and passing the results to echo

bashcommand-substitutionechoshell

When I do ls | grep png the output of grep is:

2015-05-15-200203_1920x1080_scrot.png 
2015-05-16-025536_1920x1080_scrot.png

(filename,newline,filename,newline)

then, echo $(ls | grep png) outputs:

2015-05-15-200203_1920x1080_scrot.png 2015-05-16-025536_1920x1080_scrot.png

(filename,space from word splitting,filename,newline !!from echo!!)

That is all ok, but when I do this to prevent the word splitting: echo "$(ls | grep png)", the output is:

2015-05-15-200203_1920x1080_scrot.png 
2015-05-16-025536_1920x1080_scrot.png

And my question is, where is the second newline (one should be from grep and one from echo)?

Best Answer

That's newline from echo, you can verify by using echo -n to suppress trailing newline:

echo -n "$(ls | grep png)"

Command substitution remove all trailing newlines, last newline was added by echo, grep has nothing to do here.