I have this a script containing a function and a function call. Inside the function there's an heredocument:


DWA() {
    mysql -u root -p <<-MYSQL

The problem

The execution breaks with an error regarding heredocument delimiter (likely, due to the delimiter MYSQL being indented).

The problem didn't happen when I removed all leads (whitespaces/tabs).

My question

Given functions strip all leading tabs (I don't know about other types of leads, like whitespaces), why do I encounter this problem and what, if at all, can be done against that?

  • 2
    Functions strip all leads? – Jesse_b Dec 2 '17 at 23:35
  • I've read in the past that they are, or I was confused with something else. – Arcticooling Dec 2 '17 at 23:39
  • 2
    Are you sure you're indenting with tabs and not with spaces? – igal Dec 2 '17 at 23:40
  • @Arcticooling, I don't think I have ever heard anything like that however there is a lot I haven't heard about. I think it's likely whatever you read does not apply in this case. Here docs are sort of a special block of it's own, and as far as I know they require your ending delimiter to be at the beginning of the line with no leading whitespace. – Jesse_b Dec 2 '17 at 23:45
  • I don't understand. I didn't ask why you're indenting. I just asked if you're sure that you're using tabs. – igal Dec 2 '17 at 23:57

You're probably not indenting your heredoc with tabs. Every line of the heredoc must be indented with a tab, including the first line (where the delimiter is introduced). Here is a test case for you:

echo -e 'function heredoc() {\n\tcat <<-HEREDOC\n\t\tThis is a test\tHEREDOC\n} heredoc' > heredoc.sh

Try running that command and then running heredoc.sh. You should get the following output:

This is a test.

Alternatively, here is the same script but with the first line indented with spaces instead of a tab:

    echo -e 'function heredoc() {\n    cat <<-HEREDOC\n\t\tThis is a test\tHEREDOC\n} heredoc' > heredoc2.sh

If we run heredoc2.sh we get the following error output:

bash heredoc2.sh 
heredoc2.sh: line 4: warning: here-document at line 2 delimited by end-of-file (wanted `HEREDOC')
heredoc2.sh: line 5: syntax error: unexpected end of file

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.