Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Maintain line breaks in output from subshell

Tags:

linux

bash

When I execute a subshell to obtain output of a command, the line breaks are lost.

For example:

filenames=$(grep 'foobar' /some/dir)
echo $filenames

Assuming there is more than 1 file in /some/dir that contains the string "foobar", those filenames will be printed in one long space-separated line instead of 1 filename per line.

I can't just use tr to convert the spaces back to line breaks since the filenames could have spaces in them anyway.

Is there a way to maintain the line breaks?

like image 721
fukawi2 Avatar asked May 14 '13 05:05

fukawi2


1 Answers

Quote the variable to print the newlines:

filenames=$(grep 'foobar' /some/dir)
echo "$filenames"
like image 75
P.P Avatar answered Nov 03 '22 11:11

P.P