place a multi-line output inside a variable

一曲冷凌霜 提交于 2019-12-23 08:01:17

问题


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

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?


回答1:


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

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



回答2:


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

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 "$LINES"

Note, that the assignment does not need 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.



来源:https://stackoverflow.com/questions/8713158/place-a-multi-line-output-inside-a-variable

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!