Take the 2-minute tour ×
Server Fault is a question and answer site for professional system and network administrators. It's 100% free, no registration required.

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)
share|improve this question
    
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

1 Answer 1

up vote 4 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.

share|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

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

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