如何在 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
How to insert a new line in Linux shell script?
提问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 echo
statements is to insert an echo
without arguments, for example:
在echo
语句之间插入新行的最简单方法是插入echo
不带参数的,例如:
echo Create the snapshots
echo
echo Snapshot created
That is, echo
without any arguments will print a blank line.
也就是说,echo
没有任何参数将打印一个空行。
Another alternative to use a single echo
statement with the -e
flag and embedded newline characters \n
:
使用echo
带有-e
标志和嵌入换行符的单个语句的另一种替代方法\n
:
echo -e "Create the snapshots\n\nSnapshot created"
However, this is not portable, as the -e
flag 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 \n
at the end, as printf
doesn't append a newline automatically as echo
does.
这在许多系统中更可靠,尽管它不符合 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 ?printf
command may accept arguments and needs a format control string similar (but not exactly the same) to the one for the standard Cprintf(3)function...
这 ?printf
command 可以接受参数并需要一个与标准C printf(3)函数的格式控制字符串类似(但不完全相同)的格式控制字符串...
回答by Ohad Cohen
echo $'Create the snapshots\nSnapshot created\n'