Solved Heredoc within a function

I'm trying to use functions in a shell script and can't get a heredoc within a function working.

Bash:
func1()
{
cat <<EOF >abc
cd /
ls -al
EOF
}

func1

I get end of file unexpected (expecting "}")
Any ideas?
 
Any ideas?
Could be a missing close bracket somewhere.

I tried your function, it works, after executing the following script there is a file abc with the expected content in it.
Code:
01 : ls
file1                file2                test_here_doc_in_func.sh
01 :
01 : cat test_here_doc_in_func.sh
#!/bin/sh
func1()
{
cat <<EOF >abc
cd /
ls -al
EOF
}

func1
01 :
01 : sh test_here_doc_in_func.sh
01 :
01 : ls
abc                file1                file2                test_here_doc_in_func.sh
01 :
01 : cat abc
cd /
ls -al
01 :
 
Actually the code I posted was not correctly laid out, I had problems pasting from my editor...
It should have looked like this:-
Code:
func1()
{
    cat <<EOF >abc
    cd /
    ls -al
    EOF
}

func1

I've now discovered that it's the indentation which triggers the error, and more specfically the indentation of EOF.

Thanks for comfirming that it did work normally for you.
 
Yes, and the restrictions about "the ending" extend even further than indentation.
The POSIX - Shell Command Language at 2.7.4 Here-Document (my bolding}:
2.7.4 Here-Document

The redirection operators "<<" and "<<-" both allow redirection of subsequent lines read by the shell to the input of a command. The redirected lines are known as a "here-document".

The here-document shall be treated as a single word that begins after the next <newline> and continues until there is a line containing only the delimiter and a <newline>, with no <blank> characters in between. Then the next here-document starts, if there is one. The format is as follows:

[n]<<word
here-document
delimiter
...
 
This what caught to out:-
The here-document shall be treated as a single word that begins after the next <newline> and continues until there is a line containing only the delimiter and a <newline>
I had a space or tab preceding the delimiter.
 
Back
Top