如何在bash函数中使用heredoc?

是否有可能在一个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 

环境:

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

你的代码对我来说看起来很好,所以我把它复制到行,它为我工作:

  • 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)

是否可以手动重新input文件,以确保不会丢失或添加空格/制表符等?

另外,你怎么执行它? 我做了一个chmod +x test.sh ,然后是./test.sh

编辑:我收到了同样的错误,当你在closuresHEREDOC的行的开头添加一个空格。