如何在Linux Shell脚本中插入新行? [英] How to insert a new line in Linux shell script?
问题描述
我想在多个echo语句之间插入新行.我已经尝试过echo "hello\n"
,但是它不起作用.正在打印\n
.我想要这样的期望输出:
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:
Create the snapshots
Snapshot created
推荐答案
在echo
语句之间插入新行的最简单方法是插入不带参数的echo
,例如:
The simplest way to insert a new line between echo
statements is to insert an echo
without arguments, for example:
echo Create the snapshots
echo
echo Snapshot created
也就是说,没有任何参数的echo
将打印空白行.
That is, echo
without any arguments will print a blank line.
使用带有-e
标志和嵌入式换行符\n
的单个echo
语句的另一种选择:
Another alternative to use a single echo
statement with the -e
flag and embedded newline characters \n
:
echo -e "Create the snapshots\n\nSnapshot created"
但是,这不是可移植的,因为-e
标志并非在所有系统中都一致工作.如果您确实要执行此操作,则更好的方法是使用printf
:
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
:
printf "Create the snapshots\n\nSnapshot created\n"
尽管它不兼容POSIX,但在许多系统中都能更可靠地工作.请注意,您必须手动在末尾添加\n
,因为printf
不会像echo
那样自动添加换行符.
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.
这篇关于如何在Linux Shell脚本中插入新行?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!