Bash 中的回显换行符打印文字 \n

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/8467424/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-09 21:19:47  来源:igfitidea点击:

Echo newline in Bash prints literal \n

bashechonewline

提问by Sergey

In Bash, tried this:

在 Bash 中,试过这个:

echo -e "hello\nworld"

But it doesn't print a newline, only \n. How can I make it print the newline?

但它不打印换行符,只打印\n. 我怎样才能让它打印换行符?

I'm using Ubuntu 11.04.

我正在使用 Ubuntu 11.04。

回答by sth

You could use printfinstead:

你可以printf改用:

printf "hello\nworld\n"

printfhas more consistent behavior than echo. The behavior of echovaries greatly between different versions.

printf具有比 更一致的行为echoecho不同版本之间的行为差异很大。

回答by choroba

Are you sure you are in bash? Works for me, all four ways:

你确定你在 bash 吗?对我有用,所有四种方式:

echo -e "Hello\nworld"
echo -e 'Hello\nworld'
echo Hello$'\n'world
echo Hello ; echo world

回答by Vanuan

echo $'hello\nworld'

prints

印刷

hello
world

$''strings use ANSI C Quoting:

$''字符串使用ANSI C 引用

Words of the form $'string'are treated specially. The word expands to string, with backslash-escaped characters replaced as specified by the ANSI C standard.

表格中的词被特殊处理。该单词扩展为string,并按照 ANSI C 标准的规定替换反斜杠转义字符。$'string'

回答by Nayeem Zen

You could always do echo "".

你总能做到echo ""

e.g.

例如

echo "Hello"
echo ""
echo "World"

回答by Harsha Biyani

Try

尝试

echo -e "hello\nworld"
hello
world

worked for me in nanoeditor.

nano编辑器中对我来说有效。

From the man page:

从手册页:

-eenable interpretation of backslash escapes

-e启用反斜杠转义的解释

回答by Uncle Iroh

In the off chance that someone finds themselves beating their head against the wall trying to figure out why a coworker's script won't print newlines, look out for this ->

如果有人发现自己用头撞墙试图弄清楚为什么同事的脚本不会打印换行符,请注意这个 ->

#!/bin/bash
function GET_RECORDS()
{
   echo -e "starting\n the process";
}

echo $(GET_RECORDS);

As in the above, the actual running of the method may itself be wrapped in an echo which supersedes any echos that may be in the method itself. Obviously I watered this down for brevity, it was not so easy to spot!

如上所述,该方法的实际运行本身可以包含在一个回声中,该回声取代了可能在该方法本身中的任何回声。显然,为了简洁起见,我淡化了这一点,它不是那么容易发现!

You can then inform your comrades that a better way to execute functions would be like so:

然后你可以告诉你的同志,一个更好的执行函数的方法是这样的:

#!/bin/bash
function GET_RECORDS()
{
   echo -e "starting\n the process";
}

GET_RECORDS;

回答by Sathesh

This works for me in Raspbian,

这在 Raspbian 中对我有用,

echo -e "hello\nworld"

回答by R Sun

Simply type

只需输入

echo

to get a new line

换一条新线

回答by alinsoar

str='hello\nworld'
$ echo | sed "i$str"
hello
world

回答by vanishedzhou

It works for me in CentOS:

它在 CentOS 中对我有用:

echo -e ""hello\nworld""