Bash syntax error: unexpected end of file

2019-01-02 15:18发布

Forgive me for this is a very simple script in Bash. Here's the code:

#!/bin/bash
# june 2011

if [ $# -lt 3 -o $# -gt 3 ]; then
   echo "Error... Usage: $0 host database username"
   exit 0
fi

after running sh file.sh:

syntax error: unexpected end of file

标签: bash syntax
13条回答
妖精总统
2楼-- · 2019-01-02 15:46

I think file.sh is with CRLF line terminators.

run

dos2unix file.sh

then the problem will be fixed.

You can install dos2unix in ubuntu with this:

sudo apt-get install dos2unix
查看更多
看淡一切
3楼-- · 2019-01-02 15:50

Make sure the name of the directory in which the .sh file is present does not have a space character. e.g: Say if it is in a folder called 'New Folder', you're bound to come across the error that you've cited. Instead just name it as 'New_Folder'. I hope this helps.

查看更多
梦醉为红颜
4楼-- · 2019-01-02 15:51

I just cut-and-pasted your example into a file; it ran fine under bash. I don't see any problems with it.

For good measure you may want to ensure it ends with a newline, though bash shouldn't care. (It runs for me both with and without the final newline.)

You'll sometimes see strange errors if you've accidentally embedded a control character in the file. Since it's a short script, try creating a new script by pasting it from your question here on StackOverflow, or by simply re-typing it.

What version of bash are you using? (bash --version)

Good luck!

查看更多
爱死公子算了
5楼-- · 2019-01-02 15:56

i also just got this error message by using the wrong syntax in an if clause

  • else if (syntax error: unexpected end of file)
  • elif (correct syntax)

i debugged it by commenting bits out until it worked

查看更多
时光乱了年华
6楼-- · 2019-01-02 15:56

I got this answer from this similar problem on StackOverflow

Open the file in Vim and try

:set fileformat=unix

Convert eh line endings to unix endings and see if that solves the issue. If editing in Vim, enter the command :set fileformat=unix and save the file. Several other editors have the ability to convert line endings, such as Notepad++ or Atom

Thanks @lemongrassnginger

查看更多
步步皆殇っ
7楼-- · 2019-01-02 15:57

Apparently, some versions of the shell can also emit this message when the final line of your script lacks a newline.

查看更多
登录 后发表回答