在 Bash 中,heredoc 可以用于在脚本中嵌入多行文本。但是,当尝试使用动态生成的 heredoc 时,有时会遇到“here-document at line XX delimited by end-of-file”错误。
以下是一个示例,演示了如何使用变量生成 heredoc:
variable=$(cat << HEREDOC
This is a sample heredoc.
It can include multiple lines.
HEREDOC)
但是,如果将此代码放入另一个 heredoc 中,则会出现错误:
variable2=$(cat << HEREDOC2
This is a second heredoc.
It includes the first heredoc as a variable: $variable.
HEREDOC2)
运行该代码将导致以下错误消息:
-bash: warning: here-document at line 2 delimited by end-of-file (wanted `HEREDOC2')
-bash: error: unclosed heredoc `HEREDOC2'
这是因为 Bash 将尝试将第二个 heredoc 放入第一个 heredoc 中,但由于缺少 heredoc2 终止符,因此会出现错误。
要解决此错误,请将第二个 heredoc 放入另一个变量中,然后在第二个 heredoc 中引用该变量。例如:
variable=$(cat << HEREDOC
This is a sample heredoc.
It can include multiple lines.
HEREDOC)
variable2=$(cat << HEREDOC2
This is a second heredoc.
It includes the first heredoc as a variable: $variable.
HEREDOC2
)
echo $variable2
这将打印出以下输出:
This is a second heredoc.
It includes the first heredoc as a variable: This is a sample heredoc.
It can include multiple lines.
通过将第一个 heredoc 的内容放入变量中,并在第二
上一篇:Bash-迭代复制文件