Bash script: Unexpected end of file error

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. It is best to use syntax highlighting to quickly figure out where you have a mismatched structure in your script.

In this tutorial, you will see a few examples of what causes the Unexpected end of file error, and suggestions on how to fix it.

In this tutorial you will learn:

  • What causes the Unexpected end of file error
  • How to find the cause of the error with syntax highlighting text editors
Receiving the Unexpected end of file error from executing a Bash script on Linux
Receiving the Unexpected end of file error from executing a Bash script on Linux
Software Requirements and Linux Command Line Conventions
Category Requirements, Conventions or Software Version Used
System Any Linux distro
Software Bash shell (installed by default)
Other Privileged access to your Linux system as root or via the sudo command.
Conventions # – requires given linux commands to be executed with root privileges either directly as a root user or by use of sudo command
$ – requires given linux commands to be executed as a regular non-privileged user

Bash script: Unexpected end of file error



Twitter icon Follow LinuxConfig.org on Twitter for the latest tips and tricks about Linux!


The error will look something like this:

$ ./test.sh 
./test.sh: line 3: unexpected EOF while looking for matching `"'
./test.sh: line 4: syntax error: unexpected end of file

As you can see, Bash already gives us some helpful information about how to troubleshoot the error, by giving us the line number where it encountered the problem. In this case, we even get some extra info, with the error telling us that we are missing a double quote " character. Easy fix.

Another thing we can do is use an appropriate file editor for Bash scripts. Something like vim will automatically indent our Bash script and color code according to syntax, making it much easier to spot errors.

Take a look at the example below. It is easy to see that the if statement has not been closed, because we should see a corresponding fi with the same indentation.

An unclosed if statement, which causes an unexpected end of file error
An unclosed if statement, which causes an unexpected end of file error

Closing Thoughts

It is common to run into an unexpected end of file error, as we are human and can easily forget to close one of structures in the Bash script, whether it be a quote, or to end a conditional statement or loop. By using the error message to figure out which line has the problem, and by using a text editor that recognized Bash script syntax, we can minimize our errors and quickly spot the ones we make.



Comments and Discussions
Linux Forum