简体   繁体   English

Echo newline in Bash 打印文字 \n

[英]Echo newline in Bash prints literal \n

How do I print a newline?如何打印换行符? This merely prints \n :这只是打印\n

$ echo -e "Hello,\nWorld!"
Hello,\nWorld!

You could use printf instead:你可以使用printf代替:

printf "hello\nworld\n"

printf has more consistent behavior than echo . printfecho具有更一致的行为。 The behavior of echo varies greatly between different versions. echo的行为在不同版本之间差异很大。

Make sure you are in Bash.确保你在 Bash 中。 All these four ways work for me:所有这四种方式都对我有用:

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

prints印刷

hello
world

$'' strings use ANSI C Quoting : $''字符串使用ANSI C 引用

Words of the form $' string ' are treated specially. $' string '形式的单词被特殊处理。 The word expands to string , with backslash-escaped characters replaced as specified by the ANSI C standard.该单词扩展为string ,并按照 ANSI C 标准的规定替换反斜杠转义字符。

You could always do echo "" .你总是可以做echo ""

For example,例如,

echo "Hello,"
echo ""
echo "World!"

Try尝试

echo -e "hello\nworld"
hello
world

It worked for me in the nano editor.它在nano编辑器中对我有用

From the man page:从手册页:

-e enable interpretation of backslash escapes -e启用反斜杠转义的解释

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;

Simply type只需输入

echo

to get a new line换一条新线

这在Raspbian 中对我有用

echo -e "hello\\nworld"

POSIX 7 on echo POSIX 7 回声

http://pubs.opengroup.org/onlinepubs/9699919799/utilities/echo.html http://pubs.opengroup.org/onlinepubs/9699919799/utilities/echo.html

-e is not defined and backslashes are implementation defined: -e未定义,反斜杠是实现定义的:

If the first operand is -n, or if any of the operands contain a <backslash> character, the results are implementation-defined.如果第一个操作数是 -n,或者如果任何操作数包含 <反斜杠> 字符,则结果是实现定义的。

unless you have an optional XSI extension.除非您有可选的 XSI 扩展。

So I recommend that you should use printf instead, which is well specified:所以我建议你应该使用printf代替,它是明确指定的:

format operand shall be used as the format string described in XBD File Format Notation [...]格式操作数应用作 XBD 文件格式表示法中描述的格式字符串 [...]

the File Format Notation : 文件格式符号

\\n <newline> Move the printing position to the start of the next line. \\n <newline> 将打印位置移动到下一行的开头。

Also keep in mind that Ubuntu 15.10 and most distros implement echo both as:还要记住,Ubuntu 15.10 和大多数发行版都将echo实现为:

  • a Bash built-in: help echo Bash 内置: help echo
  • a standalone executable: which echo一个独立的可执行文件: which echo

which can lead to some confusion.这可能会导致一些混乱。

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

For only the question asked (not special characters etc) changing only double quotes to single quotes.仅针对所问的问题(不是特殊字符等)仅将双引号更改为单引号。

echo -e 'Hello,\nWorld!'

Results in:结果是:

Hello,
World!

You can also do:你也可以这样做:

echo "hello
world"

This works both inside a script and from the command line.这在脚本中和命令行中都有效。

On the command line, press Shift + Enter to do the line break inside the string.在命令行上,按Shift + Enter在字符串内进行换行。

This works for me on my macOS and my Ubuntu 18.04 (Bionic Beaver) system.这适用于我的 macOS 和我的Ubuntu 18.04 (Bionic Beaver) 系统。

它在 CentOS 中对我有用:

echo -e ""hello\nworld""

I just use echo without any arguments:我只使用 echo 不带任何参数:

echo "Hello"
echo
echo "World"

My script:我的脚本:

echo "WARNINGS: $warningsFound WARNINGS FOUND:\n$warningStrings

Output:输出:

WARNING : 2 WARNINGS FOUND:\nWarning, found the following local orphaned signature file:

On my Bash script I was getting mad as you until I've just tried:在我的 Bash 脚本中,我和你一样生气,直到我刚刚尝试过:

echo "WARNING : $warningsFound WARNINGS FOUND:
$warningStrings"

Just hit Enter where you want to insert that jump.只需在要插入该跳转的位置按 Enter即可。 The output now is:现在的输出是:

WARNING : 2 WARNINGS FOUND:
Warning, found the following local orphaned signature file:

There is a new parameter expansion added in Bash 4.4 that interprets escape sequences: Bash 4.4 中添加了一个新的参数扩展来解释转义序列:

${parameter@operator} - E operator

The expansion is a string that is the value of parameter with backslash escape sequences expanded as with the $'…' quoting mechanism.扩展是一个字符串,它是带有反斜杠转义序列的参数值,就像$'…'引用机制一样扩展。

$ foo='hello\nworld'
$ echo "${foo@E}"
hello
world

One more entry here for those that didn't make it work with any of these solutions, and need to get a return value from their function:对于那些没有使其适用于任何这些解决方案并且需要从其函数中获取返回值的人,这里还有一个条目:

function foo()
{
    local v="Dimi";
    local s="";
    .....
    s+="Some message here $v $1\n"
    .....
    echo $s
}

r=$(foo "my message");
echo -e $r;

Only this trick worked on a Linux system I was working on with this Bash version:只有这个技巧在我使用这个 Bash 版本的 Linux 系统上有效:

GNU bash, version 2.2.25(1)-release (x86_64-redhat-linux-gnu)

This could better be done as这可以更好地做为

x="\n"
echo -ne $x

-e option will interpret backslahes for the escape sequence -e 选项将解释转义序列的反斜杠
-n option will remove the trailing newline in the output -n 选项将删除输出中的尾随换行符

PS: the command echo has an effect of always including a trailing newline in the output so -n is required to turn that thing off (and make it less confusing) PS:命令 echo 具有始终在输出中包含尾随换行符的效果,因此需要 -n 关闭该内容(并使其不那么混乱)

If you're writing scripts and will be echoing newlines as part of other messages several times, a nice cross-platform solution is to put a literal newline in a variable like so:如果您正在编写脚本并且将多次将换行符作为其他消息的一部分回显,一个不错的跨平台解决方案是将文字换行符放入变量中,如下所示:

newline='
'

echo "first line$newlinesecond line"
echo "Error: example error message n${newline}${usage}" >&2 #requires usage to be defined

You could also use echo with braces,您也可以使用带大括号的 echo,

$ (echo hello; echo world)
hello
world

This may not apply in your case, but it's something that has confused me in the past:这可能不适用于您的情况,但过去让我感到困惑的是:

Wrong错误的

Writing "hello\\nworld" in Bash gives you a string with a new-line character in it, and echo -e prints that exact string.在 Bash 中编写"hello\\nworld"会为您提供一个带有换行符的字符串,并且echo -e打印出该字符串。

Right

Writing $'hello\\nworld' or$'hello\\nworld'

"hello
world"

gives you a string with a new-line character in it, and plain echo prints that exact string.为您提供一个带有换行符的字符串,而普通的echo打印出该字符串。 Which is good, since as you've seen, echo -e isn't always supported.这很好,因为正如您所见,并不总是支持echo -e

Sometimes you can pass multiple strings separated by a space and it will be interpreted as \\n .有时您可以传递由空格分隔的多个字符串,它将被解释为\\n

For example when using a shell script for multi-line notifcations:例如,当使用 shell 脚本进行多行通知时:

#!/bin/bash
notify-send 'notification success' 'another line' 'time now '`date +"%s"`

在bash配置文件(MacOx,iTerm)中用作别名时,我必须用双引号将文本引起来。

alias helloworld="echo -e \"hello \n world\""

This got me there....这让我在那里......

outstuff=RESOURCE_GROUP=[$RESOURCE_GROUP]\\nAKS_CLUSTER_NAME=[$AKS_CLUSTER_NAME]\\nREGION_NAME=[$REGION_NAME]\\nVERSION=[$VERSION]\\nSUBNET-ID=[$SUBNET_ID]
printf $outstuff

Yields:产量:

RESOURCE_GROUP=[akswork-rg]
AKS_CLUSTER_NAME=[aksworkshop-804]
REGION_NAME=[eastus]
VERSION=[1.16.7]
SUBNET-ID=[/subscriptions/{subidhere}/resourceGroups/makeakswork-rg/providers/Microsoft.Network/virtualNetworks/aks-vnet/subnets/aks-subnet]

Backslash \\<\/code> is a special character in bash.反斜杠\\<\/code>是 bash 中的特殊字符。 To print characters like '".,<\/code> we need to put \\<\/code> in front of them.要打印像'".,<\/code>这样'".,<\/code>字符'".,<\/code>我们需要在它们前面加上\\<\/code> 。

So, to print a new line with echo, use:因此,要使用 echo 打印新行,请使用:

echo \\n

With jq :随着jq

$ jq -nr '"Hello,\nWorld"'
Hello,
World

Additional solution:附加解决方案:

In cases, you have to echo a multiline of the long contents (such as code/ configurations)在某些情况下,您必须回显多行的长内容(例如代码/配置)

For example:例如:

  • A Bash script to generate codes/ configurations用于生成代码/配置的 Bash 脚本

echo -e , printf might have some limitation echo -e , printf可能有一些限制

You can use some special char as a placeholder as a line break (such as ~ ) and replace it after the file was created using tr :您可以使用一些特殊字符作为占位符作为换行符(例如~ )并在使用tr创建文件后替换它:

echo ${content} | tr '~' '\n' > $targetFile

It needs to invoke another program ( tr ) which should be fine, IMO.它需要调用另一个应该没问题的程序( tr ),IMO。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM