如何在 Linux shell 脚本中插入新行?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/20536112/
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-08-07 01:37:54  来源:igfitidea点击:

How to insert a new line in Linux shell script?

linuxbashnewline

提问by user3086014

I want to insert a new line between multiple echo statements. I have tried echo "hello\n", but it is not working. It is printing \n. I want the desired output like this:

我想在多个 echo 语句之间插入一个新行。我试过了echo "hello\n",但它不起作用。它正在打印\n。我想要这样的所需输出:

Create the snapshots

Snapshot created

采纳答案by janos

The simplest way to insert a new line between echostatements is to insert an echowithout arguments, for example:

echo语句之间插入新行的最简单方法是插入echo不带参数的,例如:

echo Create the snapshots
echo
echo Snapshot created

That is, echowithout any arguments will print a blank line.

也就是说,echo没有任何参数将打印一个空行。

Another alternative to use a single echostatement with the -eflag and embedded newline characters \n:

使用echo带有-e标志和嵌入换行符的单个语句的另一种替代方法\n

echo -e "Create the snapshots\n\nSnapshot created"

However, this is not portable, as the -eflag doesn't work consistently in all systems. A better way if you really want to do this is using printf:

但是,这不是可移植的,因为该-e标志在所有系统中都不能一致地工作。如果您真的想这样做,更好的方法是使用printf

printf "Create the snapshots\n\nSnapshot created\n"

This works more reliably in many systems, though it's not POSIX compliant. Notice that you must manually add a \nat the end, as printfdoesn't append a newline automatically as echodoes.

这在许多系统中更可靠,尽管它不符合 POSIX。请注意,您必须\n在末尾手动添加 a ,因为printf它不会像echo那样自动添加换行符。

回答by Kalanidhi

Use this echo statement

使用这个 echo 语句

 echo -e "Hai\nHello\nTesting\n"

The output is

输出是

Hai
Hello
Testing

回答by Basile Starynkevitch

You could use the printf(1)command, e.g. like

您可以使用printf(1)命令,例如

printf "Hello times %d\nHere\n" $[2+3] 

The ?printfcommand may accept arguments and needs a format control string similar (but not exactly the same) to the one for the standard Cprintf(3)function...

这 ?printfcommand 可以接受参数并需要一个与标准C printf(3)函数的格式控制字符串类似(但不完全相同)的格式控制字符串...

回答by Ohad Cohen

echo $'Create the snapshots\nSnapshot created\n'