Bash – Capturing multiple line output into a Bash variable

bashvariables

I've got a script 'myscript' that outputs the following:

abc
def
ghi

in another script, I call:

declare RESULT=$(./myscript)

and $RESULT gets the value

abc def ghi

Is there a way to store the result either with the newlines, or with '\n' character so I can output it with 'echo -e'?

Best Answer

Actually, RESULT contains what you want — to demonstrate:

echo "$RESULT"

What you show is what you get from:

echo $RESULT

As noted in the comments, the difference is that (1) the double-quoted version of the variable (echo "$RESULT") preserves internal spacing of the value exactly as it is represented in the variable — newlines, tabs, multiple blanks and all — whereas (2) the unquoted version (echo $RESULT) replaces each sequence of one or more blanks, tabs and newlines with a single space. Thus (1) preserves the shape of the input variable, whereas (2) creates a potentially very long single line of output with 'words' separated by single spaces (where a 'word' is a sequence of non-whitespace characters; there needn't be any alphanumerics in any of the words).