如何打印新行?这只会打印\n:
$ echo -e "Hello,\nWorld!"
Hello,\nWorld!
如何打印新行?这只会打印\n:
$ echo -e "Hello,\nWorld!"
Hello,\nWorld!
当前回答
对于所问的问题(不是特殊字符等),只将双引号改为单引号。
echo -e 'Hello,\nWorld!'
结果如下:
Hello,
World!
其他回答
如果前面的答案不起作用,并且需要从函数中获取返回值:
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)
你也可以使用带括号的echo,
$ (echo hello; echo world)
hello
world
您还可以执行以下操作:
echo "hello
world"
这在脚本内部和命令行中都有效。
在命令行上,按Shift+Enter键在字符串内进行换行。
这适用于我的macOS和Ubuntu 18.04(仿生海狸)系统。
如果您正在编写脚本,并且将多次将换行符作为其他消息的一部分进行回显,那么一个不错的跨平台解决方案是在变量中添加一个文本换行符,如下所示:
newline='
'
echo "first line${newline}second line"
echo "Error: example error message n${newline}${usage}" >&2 #requires usage to be defined
有时您可以传递由空格分隔的多个字符串,它将被解释为\n。
例如,当为多行通知使用shell脚本时:
#!/bin/bash
notify-send 'notification success' 'another line' 'time now '`date +"%s"`