14

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)
3
  • 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, 2011 at 2:30
  • @jdw, here docs are present in many languages including bash.
    – Zoredache
    Nov 22, 2011 at 2:55
  • I see that now. Cool.
    – jdw
    Nov 22, 2011 at 13:32

1 Answer 1

11

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.

Further Note: A trailing space behind the closing HEREDOC can also cause this

3
  • 1
    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, 2011 at 3:44
  • 1
    Indeed! I love me some heredocs.
    – David
    Nov 22, 2011 at 8:16
  • 1
    Additionally: A trailing space behind the closing HEREDOC can also cause this (These kind of errors are really hard to track down. sigh.)
    – 0laf
    Apr 24, 2018 at 7:43

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

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