将命令输出存储到bash中的变量时

将命令输出存储到bash中的变量时

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

问题描述

我正在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.

如何将命令的输出存储到变量中并保留换行符/回车符?

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

推荐答案

引用.原因如下:

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

不带引号的外壳将$TEMP替换为其包含的字符(其中一个是换行符).然后,在调用echo之前,shell使用Internal Field Separator(IFS)将字符串拆分为多个参数,然后将所得的参数列表传递给echo.默认情况下,IFS设置为空格(空格,制表符和换行符),因此Shell将您的$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中的变量时,如何保留换行符?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

09-05 17:25