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.
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).
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):
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With