将多行输出捕获到 Bash 变量中 [英] Capturing multiple line output into a Bash variable
问题描述
我有一个输出以下内容的脚本myscript":
I've got a script 'myscript' that outputs the following:
abc
def
ghi
在另一个脚本中,我调用:
in another script, I call:
declare RESULT=$(./myscript)
和 $RESULT
获取值
abc def ghi
有没有办法用换行符或 '
' 字符存储结果,以便我可以用 'echo -e
' 输出它?
Is there a way to store the result either with the newlines, or with '
' character so I can output it with 'echo -e
'?
推荐答案
实际上,RESULT 包含了你想要的——演示:
Actually, RESULT contains what you want — to demonstrate:
echo "$RESULT"
你所展示的就是你从中得到的:
What you show is what you get from:
echo $RESULT
<小时>
正如评论中所指出的,不同之处在于 (1) 变量的双引号版本 (echo "$RESULT"
) 完全按照它在变量 — 换行符、制表符、多个空格和所有 — 而 (2) 不带引号的版本 (echo $RESULT
) 用一个空格替换一个或多个空格、制表符和换行符的每个序列.因此,(1) 保留了输入变量的形状,而 (2) 创建了一个潜在的非常长的单行输出,其中单词"由单个空格分隔(其中单词"是非空白字符的序列;需要'不能是任何单词中的任何字母数字).
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).
这篇关于将多行输出捕获到 Bash 变量中的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!