将多行输出放置在变量内
我正在 bash 中编写一个脚本,我希望它执行命令并单独处理每一行。例如:
LINES=$(df)
echo $LINES
它将返回所有用空格转换新行的输出。
示例:
如果输出应该是:
1
2
3
那么我会得到
1 2 3
如何将命令的输出放入变量中,允许新行仍然是新行,这样当我打印变量时我将得到正确的输出?
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?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
一般来说,在 bash 中
$v
在大多数情况下都是自找麻烦。几乎总是你真正的意思是双引号中的"$v"
:Generally in bash
$v
is asking for trouble in most cases. Almost always what you really mean is"$v"
in double quotes:不,不会的。
$(something)
仅删除尾随换行符。echo 的参数扩展在空格上进行分割,然后 echo 将单独的参数与空格连接起来。要保留空格,您需要再次引用:
注意,赋值不需要需要引用;扩展的结果在变量的赋值和
case
的参数中不是分词的。但它可以被引用,而且学会总是加上引号会更容易。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:
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.