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

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

当前回答

确保你在巴什。

$ echo $0
bash

这四种方式对我都有效:

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

其他回答

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

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

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

改用printf:

printf "hello\nworld\n"

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

如果您正在编写脚本,并且将多次将换行符作为其他消息的一部分进行回显,那么一个不错的跨平台解决方案是在变量中添加一个文本换行符,如下所示:

newline='
'

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

确保你在巴什。

$ echo $0
bash

这四种方式对我都有效:

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

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

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

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