如何在bash存储命令输出变量时我preserve换行符? [英] How do I preserve line breaks when storing a command output to a variable in bash?

查看:106
本文介绍了如何在bash存储命令输出变量时我preserve换行符?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在Linux上使用bash shell的。我有这个简单的脚本...

I’m using bash shell on Linux. I have this simple script …

#!/bin/bash

TEMP=`sed -n '/'"Starting deployment of"'/,/'"Failed to start context"'/p' "/usr/java/jboss/standalone/log/server.log" | tac | awk '/'"Starting deployment of"'/ {print;exit} 1' | tac`
echo $TEMP

然而,当我运行此脚本

However, when I run this script

./temp.sh

所有的输出打印,而不回车/新行。不知道如果我存储输出至$ TEMP,或echo命令本身的方式。

all the output is printed without the carriage returns/new lines. Not sure if its the way I’m storing the output to $TEMP, or the echo command itself.

如何将命令的输出存储到一个变量,preserve换行/回车?

How do I store the output of the command to a variable and preserve the line breaks/carriage returns?

推荐答案

引用的变量。这里是为什么:

Quote your variables. Here is it why:

$ f="fafafda
> adffd
> adfadf
> adfafd
> afd"

$ echo $f
fafafda adffd adfadf adfafd afd

$ echo "$f"
fafafda
adffd
adfadf
adfafd
afd

不带引号,外壳替换 $ TEMP 与它所包含的字符(其中之一是一个换行符)。然后,在调用之前回声 shell把使用内部字段分隔符(IFS)的字符串转换成多个参数,并传递造成的参数列表回声。默认情况下, IFS 设置为空白(空格,制表符和换行符),所以外壳砍下你的 $ TEMP 串入参数,它永远不会看到新行,因为shell认为它是一个分隔符,就像一个空间。

Without quotes, the shell replaces $TEMP with the characters it contains (one of which is a newline). Then, before invoking echo shell splits that string into multiple arguments using the Internal Field Separator (IFS), and passes that resulting list of arguments to echo. By default, the IFS is set to whitespace (spaces, tabs, and newlines), so the shell chops your $TEMP string into arguments and it never gets to see the newline, because the shell considers it a separator, just like a space.

这篇关于如何在bash存储命令输出变量时我preserve换行符?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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