Bash 中的多行回显

有时我们需要使用多行输出。在通用编程语言中,我们可以使用 \n 创建一个新行;这个任务在 Bash 脚本中有点复杂。

我们不能像在另一种编程语言上那样直接使用像 \n 这样的东西。本文将讨论如何在 Bash 上创建多行输出。

此外,为了使主题更容易,我们将使用一些带有适当解释的示例。现在,我们将在这里看到两种方法。

在 Bash 中使用关键字 cat 创建多行输出

我们还可以使用关键字 cat 创建多行输出。你可以按照示例代码使用此方法创建多行输出。

cat <<'END'
This is the first line,
This is the second line
This is the third line
END

查看代码,你可以看到我们在代码的开头使用了 cat <<'END' 行。这将继续显示输出,直到 END

请记住,你可以选择任何带有 cat <<'END' 行的标签,但你需要以与开头使用的标签相同的标签结尾。所以我们可以说一般的语法是:

cat <<'YOUR_TAG'
-
- Your output here
-
YOUR_TAG

运行示例代码后,你将获得以下输出。

This is the first line,
This is the second line
This is the third line

使用关键字 print 在 Bash 中创建多行输出

我们还可以使用关键字 print 获得与前面示例相同的输出。你可以按照以下示例创建多行输出。

printf '%s\n' \
'This is the first line,' \
'This is the second line' \
'This is the third line'

因此,你可以为此目的使用此通用语法。

printf '%s\n' \
'YOUR FIRST LINE' \
'YOUR SECOND LINE' \
'YOUR THIRD LINE'

正如你在代码中看到的,我们从 '%s\n' 开始。这是为了在每次''结束时在新行中显示输出。

此外,我们需要使用符号\来表示一个新行。请记住,你必须将所有内容都放在引号中;否则,它将计为一行。

运行示例代码后,你将获得以下输出。

This is the first line,
This is the second line
This is the third line

本文中使用的所有代码都是用 Bash 编写的。它仅适用于 Linux Shell 环境。