I’m using bash shell on Linux. I have this simple script …
我在Linux上使用bash shell。我有这个简单的脚本……
#!/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
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.
所有输出都是打印的,没有回车/新行。不确定是我将输出存储为$TEMP,还是echo命令本身。
How do I store the output of the command to a variable and preserve the line breaks/carriage returns?
如何将命令的输出存储到一个变量中,并保存换行/回车?
1 个解决方案
#1
90
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
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.
没有引号,shell将$TEMP替换为它所包含的字符(其中之一是换行)。然后,在调用echo shell之前,使用内部字段分隔符(IFS)将该字符串分割成多个参数,并将产生的参数列表传递给echo。默认情况下,IFS被设置为空格(空格、制表符和换行符),因此shell将$TEMP字符串分割为参数,并且它永远看不到换行符,因为shell将它视为分隔符,就像空间一样。
#1
90
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
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.
没有引号,shell将$TEMP替换为它所包含的字符(其中之一是换行)。然后,在调用echo shell之前,使用内部字段分隔符(IFS)将该字符串分割成多个参数,并将产生的参数列表传递给echo。默认情况下,IFS被设置为空格(空格、制表符和换行符),因此shell将$TEMP字符串分割为参数,并且它永远看不到换行符,因为shell将它视为分隔符,就像空间一样。