且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

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

更新时间:2023-12-05 11:49:58

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.