如何在bash函数中使用heredoc?

Lef*_*ium 13 ubuntu bash

是否可以在 bash 函数中插入一个heredoc

下面的简单示例会导致错误: ./heredoc_in_function.sh: 10: Syntax error: end of file unexpected (expecting "}")

#!/bin/sh

my_function () {
cat <<HEREDOC
heredoc contents
HEREDOC
}

my_function
Run Code Online (Sandbox Code Playgroud)

环境:

  • Ubuntu 11.04 (GNU/Linux 2.6.38-8-server x86_64)
  • GNU bash,版本 4.2.8(1)-release (x86_64-pc-linux-gnu)

Dav*_*vid 10

你的代码对我来说看起来不错,所以我一行一行地复制它,它对我有用:

  • OSX 10.7,bash 3.2.48(1)-release (x86_64-apple-darwin11)。
  • Ubuntu 10.04.3,bash 4.1.5(1)-release (x86_64-pc-linux-gnu)

您是否可以手动重新键入文件以确保您没有丢失或添加空格/制表符/等?

另外,你是如何执行的?我做了一个chmod +x test.sh然后./test.sh

编辑:当我在行的开头添加一个空格并关闭 HEREDOC 时,我收到了与您相同的错误。

进一步注意:收盘后的尾随空格HEREDOC也可能导致这种情况