Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Bash syntax error: unexpected end of file

Tags:

syntax

bash

People also ask

What is unexpected end of file in bash?

An Unexpected end of file error in a Bash script usually occurs when you there is a mismatched structure somewhere in the script. If you forget to close your quotes, or you forget to terminate an if statement, while loop, etc, then you will run into the error when you try to execute your Bash script.

What does Unexpected end of file mean?

You are running a Bash script, and you see a syntax error: Unexpected end of file. What does it mean? This can happen if you create your script using Windows. Why? Because Windows uses a combination of two characters, Carriage Return and Line Feed, as line break in text files (also known as CRLF).

How do you end a Bash script?

There are many methods to quit the bash script, i.e., quit while writing a bash script, while execution, or at run time. One of the many known methods to exit a bash script while writing is the simple shortcut key, i.e., “Ctrl+X”. While at run time, you can exit the code using “Ctrl+Z”.


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

Another thing to check (just occured to me):

  • terminate bodies of single-line functions with semicolon

I.e. this innocent-looking snippet will cause the same error:

die () { test -n "$@" && echo "$@"; exit 1 }

To make the dumb parser happy:

die () { test -n "$@" && echo "$@"; exit 1; }

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


an un-closed if => fi clause will raise this as well

tip: use trap to debug, if your script is huge...

e.g.

set -x
trap read debug

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