here-document gives 'unexpected end of file' error

心已入冬 提交于 2019-11-25 23:10:07

问题


I need my script to send an email from terminal. Based on what I\'ve seen here and many other places online, I formatted it like this:

/var/mail -s \"$SUBJECT\" \"$EMAIL\" << EOF
Here\'s a line of my message!
And here\'s another line!
Last line of the message here!
EOF

However, when I run this I get this warning:

myfile.sh: line x: warning: here-document at line y delimited by end-of-file (wanted \'EOF\')

myfile.sh: line x+1: syntax error: unexpected end of file

...where line x is the last written line of code in the program, and line y is the line with /var/mail in it. I\'ve tried replacing EOF with other things (ENDOFMESSAGE, FINISH, etc.) but to no avail. Nearly everything I\'ve found online has it done this way, and I\'m really new at bash so I\'m having a hard time figuring it out on my own. Could anyone offer any help?


回答1:


The EOF token must be at the beginning of the line, you can't indent it along with the block of code it goes with.

If you write <<-EOF you may indent it, but it must be indented with Tab characters, not spaces. So it still might not end up even with the block of code.

Also make sure you have no whitespace after the EOF token on the line.




回答2:


The line that starts or ends the here-doc probably has some non-printable or whitespace characters (for example, carriage return) which means that the second "EOF" does not match the first, and doesn't end the here-doc like it should. This is a very common error, and difficult to detect with just a text editor. You can make non-printable characters visible for example with cat:

cat -A myfile.sh

Once you see the output from cat -A the solution will be obvious: remove the offending characters.




回答3:


Please try to remove the preceeding spaces before EOF:-

/var/mail -s "$SUBJECT" "$EMAIL" <<-EOF

Using <tab> instead of <spaces> for ident AND using <<-EOF works fine.

The "-" removes the <tabs>, not <spaces>, but at least this works.




回答4:


Note one can also get this error if you do this;

while read line; do
  echo $line
done << somefile

Because << somefile should read < somefile in this case.




回答5:


Along with the other answers mentioned by Barmar and Joni, I've noticed that I sometimes have to leave a blank line before and after my EOF when using <<-EOF.



来源:https://stackoverflow.com/questions/18660798/here-document-gives-unexpected-end-of-file-error

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!