bash 将多行输出放在变量中

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/8713158/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-18 01:14:33  来源:igfitidea点击:

place a multi-line output inside a variable

bashbash4

提问by ufk

I'm writing a script in bash and I want it to execute a command and to handle each line separately. for example:

我正在用 bash 编写一个脚本,我希望它执行一个命令并分别处理每一行。例如:

LINES=$(df)
echo $LINES

it will return all the output converting new lines with spaces.

它将返回所有输出转换为空格的新行。

example:

例子:

if the output was supposed to be:

如果输出应该是:

1
2
3

then I would get

然后我会得到

1 2 3

how can I place the output of a command into a variable allowing new lines to still be new lines so when I print the variable i will get proper output?

如何将命令的输出放入允许新行仍然是新行的变量中,以便在打印变量时获得正确的输出?

回答by kubanczyk

Generally in bash $vis asking for trouble in most cases. Almost always what you really mean is "$v"in double quotes.

通常在 bash$v中,大多数情况下都是自找麻烦。几乎总是你真正的意思是"$v"双引号。

LINES="`df`"     # double-quote + backtick
echo "$LINES"
OLDPATH="$PATH"

回答by Jan Hudec

No, it will not. The $(something)only strips trailing newlines.

不,不会。该$(something)只带尾随换行。

The expansion in argument to echo splits on whitespace and than echo concatenates separate arguments with space. To preserve the whitespace, you need to quote again:

echo 的参数扩展在空格上拆分,然后 echo 将单独的参数与空格连接起来。要保留空格,您需要再次引用:

echo "$LINES"

Note, that the assignment does notneed to be quoted; result of expansion is not word-split in assignment to variable and in argument to case. But it can be quoted and it's easier to just learn to just always put the quotes in.

请注意,这样的决定也并不需要被引用; 扩展的结果在赋值给变量和在参数中没有分词case。但是它可以被引用,而且学习总是把引号放在里面会更容易。