Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Capturing multiple line output into a Bash variable

Tags:

variables

bash

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'?

like image 448
Parker Avatar asked Mar 05 '09 04:03

Parker


People also ask

Can a bash variable have multiple lines?

Although Bash has various escape characters, we only need to concern ourselves with \n (new line character). For example, if we have a multiline string in a script, we can use the \n character to create a new line where necessary.

How do I input multiple lines in bash?

Doing: #!/bin/bash read -e -p "Multiline input=" variable; printf "'variable=%s'" "${variable}"; Typing 'multi\nline' on Multiline input= makes printf output 'variable=multinline' Typing 'multi\\nline' on Multiline input= makes printf output 'variable=multi\nline'

How do I print multiple lines in bash?

Use echo With the -e Option to Make Multi-Line String in Bash. The following bash script prints the words to multiline. txt without any extra spaces. The -e option enables the interpretation of escape characters in the variable greet .


1 Answers

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).

like image 128
Jonathan Leffler Avatar answered Sep 28 '22 01:09

Jonathan Leffler