Is it possible to insert a heredoc inside a bash function?

The trivial sample below results in an error: ./heredoc_in_function.sh: 10: Syntax error: end of file unexpected (expecting "}")

#!/bin/sh

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

my_function

Environment:

  • Ubuntu 11.04 (GNU/Linux 2.6.38-8-server x86_64)
  • GNU bash, version 4.2.8(1)-release (x86_64-pc-linux-gnu)
link|improve this question

25% accept rate
I was under the impression that heredoc was a Perl thing. Is there any reason to believe it would work in BASH? – jdw Nov 22 '11 at 2:30
@jdw, here docs are present in many languages including bash. – Zoredache Nov 22 '11 at 2:55
I see that now. Cool. – jdw Nov 22 '11 at 13:32
feedback

1 Answer

up vote 3 down vote accepted

Your code looked fine to me, so I copied it line for line and it worked for me on:

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

Is it possible for you to retype the file by hand just to make sure you aren't missing or adding spaces/tabs/etc?

Also, how are you executing it? I did a chmod +x test.sh and then ./test.sh

EDIT: I received the same error as you when I added a space at the beginning of the line with the closing HEREDOC.

link|improve this answer
Weird, it works now... Vim color syntax highlighting recognized the HEREDOC before (it doesn't if you add that space before the closing HEREDOC) I modified the original script to just use an external file, so I'm not sure what was wrong. It will be much more convenient with heredocs, though! – Leftium Nov 22 '11 at 3:44
Indeed! I love me some heredocs. – Dave Nov 22 '11 at 8:16
feedback

Your Answer

 
or
required, but never shown

Not the answer you're looking for? Browse other questions tagged or ask your own question.