将多行输出捕获到Bash变量中 [英] Capturing multiple line output into a Bash variable

查看:62
本文介绍了将多行输出捕获到Bash变量中的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个脚本"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

是否可以用换行符或'\ n'字符存储结果,以便可以用'echo -e'输出?

Is there a way to store the result either with the newlines, or with '\n' 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屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆