Error when using a bash here-doc “unexpected end o

2019-04-04 19:29发布

This question already has an answer here:

I get the following error that is flagging on the last line of my code (which is empty):

syntax error: unexpected end of file

I can't figure out why it's saying this. I'm simply trying to use a here-doc for an ssh connection:

#!/bin/sh

connectToServer() {
   ssh -t root@$1 <<- ENDSSH
      echo "Connected to server!"
   ENDSSH
}

connectToServer $1

What's wrong with this code?

EDIT

Thanks to those of you who helped me to troubleshoot this. There were a couple of things wrong with my script; I was using spaces on the line:

echo "Connected to server" 

instead of tab characters. I was also including spaces before the closing ENDSSH which was causing the EOF. These changes were a part of my problem, but the final thing that resolved it was removing an additional space character that appeared AFTER my closing ENDSSH.

标签: bash ssh
3条回答
SAY GOODBYE
2楼-- · 2019-04-04 19:51

The ENDSSH marker has to be at the left margin:

connectToServer() {
   ssh -t root@$1 << ENDSSH
      echo "Connected to server!"
ENDSSH
}

When using <<- ENDSSH you can indent the marker, but it must be indented with Tab characters, not spaces.

查看更多
别忘想泡老子
3楼-- · 2019-04-04 20:04

Problem is spaces before closing ENDSSH. Take out all the leading spaces before ENDSSH.

查看更多
走好不送
4楼-- · 2019-04-04 20:07

When using the <<- operator, only leading tabs are stripped from the here document and the line containing the marker. You appear to be indenting the closing marker with spaces, so that line appears to be part of the here document, and since the here document never closes, you reach the end of the file while parsing it.

查看更多
登录 后发表回答