如何打印新行?这只会打印\n:

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

当前回答

其他解决方案:

在某些情况下,您必须回显多行长内容(例如代码/配置)

例如:

生成代码/配置的Bash脚本

echo-e,printf可能有一些限制

您可以使用一些特殊字符作为占位符作为换行符(例如~),并在使用tr创建文件后替换它:

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

它需要调用另一个程序(tr),这应该很好,IMO。

其他回答

改用printf:

printf "hello\nworld\n"

printf在不同环境中的表现比echo更一致。

如果前面的答案不起作用,并且需要从函数中获取返回值:

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

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

只有这个技巧在我使用Bash版本开发的Linux系统上有效:

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

有时您可以传递由空格分隔的多个字符串,它将被解释为\n。

例如,当为多行通知使用shell脚本时:

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

Bash 4.4中添加了一个新的参数扩展,用于解释转义序列:

${parameter@operator}-E操作员展开是一个字符串,它是参数的值反斜杠转义序列扩展为$“…”引号机械装置

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

对于所问的问题(不是特殊字符等),只将双引号改为单引号。

echo -e 'Hello,\nWorld!'

结果如下:

Hello,
World!