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).
On the other side Unix (or Linux) only use the Line Feed character as line break.
So, let’s see what happens if we save a script using Windows and then we execute it in Linux.
Using the Windows notepad I have created a Bash script called end_of_file.sh
:
#/bin/bash
if [ $# -gt 0 ]; then
echo "More than one argument passed"
else
echo "No arguments passed"
fi
And here is the output I get when I execute it:
[ec2-user@localhost scripts]$ ./end_of_file.sh
./end_of_file.sh: line 2: $'r': command not found
./end_of_file.sh: line 8: syntax error: unexpected end of file
How do we see where the problem is?
Edit the script with the vim editor using the -b flag that runs the editor in binary mode:
[ec2-user@localhost scripts]$ vim -b end_of_file.sh
(Below you can see the content of the script)
#/bin/bash^M
^M
if [ $# -gt 0 ]; then^M
echo "More than one argument passed"^M
else^M
echo "No arguments passed"^M
fi^M
At the end of each line we see the ^M character. What is that?
It’s the carriage return we have mentioned before. Used by Windows but not by Unix (Linux) in line breaks.
To solve both errors we need to convert our script into a format that Linux understands.
The most common tool to do that is called dos2unix
.
If dos2unix is not present on your system you can use the package manager of your distribution to install it.
For instance, on my server I can use YUM (Yellowdog Updater Modified).
To search for the package I use the yum search
command:
[root@localhost ~]$ yum search dos2unix
Loaded plugins: extras_suggestions, langpacks, priorities, update-motd
====================== N/S matched: dos2unix =====================================
dos2unix.x86_64 : Text file format converters
And then the yum install
command to install it:
[root@localhost ~]$ yum install dos2unix
Loaded plugins: extras_suggestions, langpacks, priorities, update-motd
amzn2-core | 2.4 kB 00:00:00
amzn2extra-docker | 1.8 kB 00:00:00
Resolving Dependencies
--> Running transaction check
---> Package dos2unix.x86_64 0:6.0.3-7.amzn2.0.2 will be installed
--> Finished Dependency Resolution
Dependencies Resolved
==================================================================================
Package Arch Version Repository Size
==================================================================================
Installing:
dos2unix x86_64 6.0.3-7.amzn2.0.2 amzn2-core 75 k
Transaction Summary
==================================================================================
Install 1 Package
Total download size: 75 k
Installed size: 194 k
Is this ok [y/d/N]: y
Downloading packages:
dos2unix-6.0.3-7.amzn2.0.2.x86_64.rpm | 75 kB 00:00:00
Running transaction check
Running transaction test
Transaction test succeeded
Running transaction
Installing : dos2unix-6.0.3-7.amzn2.0.2.x86_64 1/1
Verifying : dos2unix-6.0.3-7.amzn2.0.2.x86_64 1/1
Installed:
dos2unix.x86_64 0:6.0.3-7.amzn2.0.2
Complete!
We are ready to convert our script using dos2unix!
[ec2-user@localhost scripts]$ dos2unix end_of_file.sh
dos2unix: converting file end_of_file.sh to Unix format ...
And now it’s time to execute it:
[ec2-user@localhost scripts]$ ./end_of_file.sh No arguments passed
It works!
If you are interested I have written an article that explains the basics of Bash script arguments.
Conclusion
I have found myself having to use the dos2unix command several times over the years.
And now you know what to do if you see the syntax error “Unexpected end of file” while running a Bash script 🙂
Related FREE Course: Decipher Bash Scripting
Related posts:
I’m a Tech Lead, Software Engineer and Programming Coach. I want to help you in your journey to become a Super Developer!
In this article, we will see how to solve «syntax error: unexpected end of File» in Linux Shell Scripting. Last night when I was working on a simple shell script to calculate sum of two numbers, I noticed an error while running the script which was totally unexpected. Then I realized although the error is straight forward but it is so common that anyone can willingly or unwillingly can do this mistake. Then after I decided to write a short article about this explaining the different scenarios which can result in unexpected end of file error.
Also Read: Solved «xx: command not found» error in Linux Shell Scripting
The simple shell script which I was working is as shown below. Here I am calculating the sum of a
and b
values and storing it in variable c
. Then finally displaying the output using echo $c
as you can see below.
cyberithub@ubuntu:~$ nano calculate
#! /bin/bash
a=5
b=7
sum()
{
c=$(($a+$b))
echo $c
}
sum()
When I tried to run above script, it gave me below error output.
cyberithub@ubuntu:~$ ./calculate ./calculate: line 13: syntax error: unexpected end of file
While unexpected end of file error can be encountered due to multiple reasons but most of the time it will be due to either parentheses or braces not opened or closed properly. Basically, the unexpected end of file error means you are trying to open something which was never closed as in bash of braces. If you need to know more about the error, then use bash -x <script_name>
. Here -x
switch is used for debugging purposes. This is more useful when you have a longer script where it is not at all easy to find errors.
Since in our case it’s a pretty small script so we can easily identify the error. So if you see the output, it says the error is in line 13
which is the below highlighted line.
cyberithub@ubuntu:~$ nano calculate #! /bin/bash a=5 b=7 sum() { c = $(($a+$b)) echo $c } sum()
You might have identified the error by now. In line 13
, opening and closing parentheses has been used to call the sum function which is incorrect. So if you remove the opening and closing parentheses like shown below and then try to run the script then you can see that sum function works properly.
cyberithub@ubuntu:~$ nano calculate #! /bin/bash a=5 b=7 sum() { c=$(($a+$b)) echo $c } sum
Output
cyberithub@ubuntu:~$ ./calculate 12
The other scenario you might encounter when you open the braces but forget to close it like in below example where you have opened the braces in below highlighted line 12
but forgot or missed closing it. In that case also you will encounter unexpected end of file
error when you try to run the script. Hence you need to be careful in closing braces.
cyberithub@ubuntu:~$ nano calculate #! /bin/bash a=5 b=7 sum() { c=$(($a+$b)) echo $c sum
Output
cyberithub@ubuntu:~$ ./calculate ./calculate: line 12: syntax error: unexpected end of file
Hope the above explanation makes sense and helps you solve the error if you are also facing unexpected end of file error. Please let me know your feedback in the comment box !!
Can someone explain why the end of the file is unexpected on line 49? (Line 49 is one line after the last line)
#!/bin/bash
timeend=$(date -u +%H%M)
timestart=$(date --date "$timeend 30 minutes ago" -u +%H%M)
firsttime=0
while true
do
if [[ $firsttime -eq 0 ]]; then
time=$timestart
increment=0
fi
if [[ $firsttime -ne true ]]; then
increment=$(( $increment + 2 ))
time=$(( $timestart + $increment ))
fi
if [[ $time -ge $timeend ]]; then
break
fi
gpnids << EOF
RADFIL = NEXRIII|CLT|TR0
RADTIM = "$time"
TITLE = 1/-2
PANEL = 0
DEVICE = gif|radar"$increment".gif|1280;1024|C
CLEAR = Y
TEXT = 1/2/2/hw
COLORS = 7
WIND =
LINE =
CLRBAR =
IMCBAR = 5/v/LL/.005;.6/.4;.01
GAREA = dset
MAP = 24 + 23 + 1/1/2 + 14 + 15/1/2
LATLON = 0
OUTPUT = t
$mapfil = lorvus.usg + hicnus.nws + hipona.nws + louhus.nws + loisus.nws
run
exit
EOF
firsttime=1
gpend
done
asked Jun 19, 2014 at 16:11
5
You should also have gotten another error which is perhaps more informative:
/home/terdon/scripts/b.sh: line 49: warning: here-document at line 21 delimited by end-of-file (wanted `EOF’)
/home/terdon/scripts/b.sh: line 50: syntax error: unexpected end of file
Your error is that you have spaces before the string that ends the heredoc. To take a simple example, this complains:
#!/bin/bash
cat << EOF
hello
EOF
But this doesn’t:
#!/bin/bash
cat << EOF
hello
EOF
answered Jun 19, 2014 at 16:20
terdonterdon
96.2k15 gold badges192 silver badges289 bronze badges
3
I get two lines that should help you work out what’s going on:
./test: line 48: warning: here-document at line 21 delimited by end-of-file (wanted `EOF')
./test: line 49: syntax error: unexpected end of file
Your heredoc
(<< EOF
) construction is incorrectly formed. It’s whitespace sensitive so you either strip it back:
...
command <<EOF
...
EOF
Or let it know you’re tabbing it(and it must be a tab):
...
command <<-EOF
...
EOF
I prefer the second because it lets you structure the script a lot better… Something your script could already benefit from.
answered Jun 19, 2014 at 16:23
Oli♦Oli
286k115 gold badges669 silver badges829 bronze badges
1
End of File warning
%>: line 49: warning: here-document at line 21 delimited by end-of-file (wanted ‘EOF’)
- heredoc is looking for the delimiter (end tag), in this case
EOF
- it’s never never recognized in your example because it is prefixed by spaces
- the end of the actual file is reached without ever finding the delimiter; hence the warning
This can be addressed by removing the spaces, or as Terndon points out using tabs — I didn’t know this
Other
Another common error for end of file error that occurs deals with whitespace issues. Generally from copying code online formatted for Windows and running it in Linux.
This can be addressed by running dos2unix
on the file to quickly convert those characters.
answered Apr 5, 2019 at 15:24
MikeMike
1111 bronze badge
If you are using vim or vi try to use the command
:set list
You will be able to see spaces between the symbol $
Sometimes It’s come in handy to figure out some unexpected behavior.
In this case delete the white spaces finished the job.
muru
189k52 gold badges460 silver badges711 bronze badges
answered Jul 12, 2015 at 13:44
PROBLEM:
Bash syntax error: unexpected end of file
Here’s the code:
[pastacode lang=”bash” manual=”%23!%2Fbin%2Fbash%0A%23%20june%202011%0A%0Aif%20%5B%20%24%23%20-lt%203%20-o%20%24%23%20-gt%203%20%5D%3B%20then%0A%20%20%20echo%20%22Error…%20Usage%3A%20%240%20host%20database%20username%22%0A%20%20%20exit%200%0AFi%0A” message=”bash code” highlight=”” provider=”manual”/]
- after running sh file.sh:
- syntax error: unexpected end of file
SOLUTION 1:
- file.sh is with CRLF line terminators.
[pastacode lang=”bash” manual=”dos2unix%20file.sh%0A” message=”bash code” highlight=”” provider=”manual”/]
then the problem will be fixed.
- You can install dos2unix in ubuntu with this:
[pastacode lang=”markup” manual=”sudo%20apt-get%20install%20dos2unix” message=”bash code” highlight=”” provider=”manual”/]
[pastacode lang=”bash” manual=”die%20()%20%7B%20test%20-n%20%22%24%40%22%20%26%26%20echo%20%22%24%40%22%3B%20exit%201%20%7D%0A” message=”bash code” highlight=”” provider=”manual”/]
SOLUTION 2:
- Terminate bodies of single-line functions with semicolon
I.e. this innocent-looking snippet will cause the same error:
[pastacode lang=”bash” manual=”%20die%20()%20%7B%20test%20-n%20%22%24%40%22%20%26%26%20echo%20%22%24%40%22%3B%20exit%201%20%7D%0A” message=”” highlight=”” provider=”manual”/]
- To make the dumb parser:
[pastacode lang=”bash” manual=”die%20()%20%7B%20test%20-n%20%22%24%40%22%20%26%26%20echo%20%22%24%40%22%3B%20exit%201%3B%20%7D%0A” message=”bash code” highlight=”” provider=”manual”/]
SOLUTION 3:
- We needed on cygwin :-
[pastacode lang=”bash” manual=”%20export%20SHELLOPTS%0A%20set%20-o%20igncr%0A” message=”bash code” highlight=”” provider=”manual”/]
in .bash_profile . This way we didn’t need to run unix2dos
SOLUTION 4:
- 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’.
Wikitechy Founder, Author, International Speaker, and Job Consultant. My role as the CEO of Wikitechy, I help businesses build their next generation digital platforms and help with their product innovation and growth strategy. I’m a frequent speaker at tech conferences and events.
Related Tags
- abs function in c,
- bash directory of script,
- bash function,
- bash shell variables,
- bash syntax error unexpected token,
- bash variable,
- bashas,
- debug shell script,
- define call,
- define echo,
- define empty,
- define function in c,
- define precede,
- double marker test wiki,
- echo function,
- environment variables in linux,
- exit function in c,
- function declaration,
- function in html,
- functions in bash,
- functions in linux shell script,
- gnu bash cve 2014 6271,
- ksh syntax error unexpected,
- line 1: syntax error: unexpected word (expecting «)»),
- line function,
- sh create array,
- sh: 1: syntax error: «(» unexpected python,
- shell script function,
- shellshock,
- shellshock test,
- syntax error ( unexpected bash array,
- syntax error ( unexpected bash function,
- syntax error ( unexpected ubuntu,
- syntax error at line unexpected,
- syntax error done unexpected,
- syntax error near unexpected token,
- syntax error unexpected c,
- syntax error unexpected end of file,
- syntax error: «(» unexpected bash,
- useful bash scripts,
- what is bash in linux,
- what is bash scripting
score:177
Accepted answer
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
score:0
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!
score:0
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.
score:0
Apparently, some versions of the shell can also emit this message when the final line of your script lacks a newline.
score:0
In Ubuntu:
$ gedit ~/.profile
Then, File -> Save as
and set end line
to Unix/Linux
score:0
For people using MacOS:
If you received a file with Windows format and wanted to run on MacOS and seeing this error, run these commands.
brew install dos2unix
sh <file.sh>
score:0
If the the script itself is valid and there are no syntax errors, then some possible causes could be:
- Invalid end-of-lines (for example,
rn
instead ofn
) - Presence of the
byte order mark
(BOM) at the beginning of the file
Both can be fixed using vim
or vi
.
To fix line endings open the file in vim and from the command mode type:
:set ff=unix
To remove the BOM use:
:set nobomb
score:0
For those who don’t have dos2unix installed (and don’t want to install it):
Remove trailing r
character that causes this error:
sed -i 's/r$//' filename
Details from this StackOverflow answer. This was really helpful.
https://stackoverflow.com/a/32912867/7286223
score:2
I was able to cut and paste your code into a file and it ran correctly. If you
execute it like this it should work:
Your «file.sh»:
#!/bin/bash
# june 2011
if [ $# -lt 3 -o $# -gt 3 ]; then
echo "Error... Usage: $0 host database username"
exit 0
fi
The command:
$ ./file.sh arg1 arg2 arg3
Note that «file.sh» must be executable:
$ chmod +x file.sh
You may be getting that error b/c of how you’re doing input (w/ a pipe, carrot,
etc.). You could also try splitting the condition into two:
if [ $# -lt 3 ] || [ $# -gt 3 ]; then
echo "Error... Usage: $0 host database username"
exit 0
fi
Or, since you’re using bash
, you could use built-in syntax:
if [[ $# -lt 3 || $# -gt 3 ]]; then
echo "Error... Usage: $0 host database username"
exit 0
fi
And, finally, you could of course just check if 3 arguments were given (clean,
maintains POSIX shell compatibility):
if [ $# -ne 3 ]; then
echo "Error... Usage: $0 host database username"
exit 0
fi
score:2
In my case, there is a redundant in the like following:
function foo() {
python tools/run_net.py
--cfg configs/Kinetics/X3D_8x8_R50.yaml
NUM_GPUS 1
TRAIN.BATCH_SIZE 8
SOLVER.BASE_LR 0.0125
DATA.PATH_TO_DATA_DIR ./afs/kinetics400
DATA.PATH_PREFIX ./afs/kinetics400 # Error
}
There is NOT a at the end of
DATA.PATH_PREFIX ./afs/kinetics400
score:4
FOR WINDOWS:
In my case, I was working on Windows OS and I got the same error while running autoconf.
- I simply open configure.ac file with my NOTEPAD++ IDE.
-
Then I converted the File with EOL conversion into Windows (CR LF) as follows:
EDIT -> EOL CONVERSION -> WINDOWS (CR LF)
score:4
Missing a closing brace on a function definition will cause this error as I just discovered.
function whoIsAnIidiot() {
echo "you are for forgetting the closing brace just below this line !"
Which of course should be like this…
function whoIsAnIidiot() {
echo "not you for sure"
}
score:7
on cygwin I needed:-
export SHELLOPTS
set -o igncr
in .bash_profile . This way I didn’t need to run unix2dos
score:7
This was happening for me when I was trying to call a function using parens, e.g.
run() {
echo hello
}
run()
should be:
run() {
echo hello
}
run
score:8
So I found this post and the answers did not help me but i was able to figure out why it gave me the error. I had a
cat > temp.txt < EOF
some content
EOF
The issue was that i copied the above code to be in a function and inadvertently tabbed the code. Need to make sure the last EOF is not tabbed.
score:11
I had the problem when I wrote «if — fi» statement in one line:
if [ -f ~/.git-completion.bash ]; then . ~/.git-completion.bash fi
Write multiline solved my problem:
if [ -f ~/.git-completion.bash ]; then
. ~/.git-completion.bash
fi
score:14
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
score:32
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
score:67
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
score:169
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; }
Related Query
- Bash Syntax Error syntax error: unexpected end of file
- syntax error: unexpected end of file in bash error
- Bash syntax error: unexpected end of file
- Syntax error : end of file unexpected (expecting «fi»)
- Bash script: syntax error: unexpected end of file
- Syntax error in Makefile: end of file unexpected (expecting «fi»)
- bash script, line 30: syntax error: unexpected end of file
- syntax error: unexpected end of file trying to run a simple bash script
- OS X Bash Script: syntax error: unexpected end of file
- Makefile: Syntax error /bin/sh: -c: syntax error: unexpected end of file
- syntax error: unexpected end of file in if statement bash file
- Debugging Bash Script: syntax error: unexpected end of file
- Bash profile syntax error: unexpected end of file
- Bash Unexpected End of File Error After Installing RVM
- bash script returns error «ERROR: syntax error at end of input LINE 1: SELECT» for psql request to copy the table to an external file
- while loop syntax error unexpected end of file
- Ubuntu bash — unexpected end of file error
- getting syntax error: unexpected end of file in bash script
- Syntax error unexpected end of file fi’ what could be the cause?
- Unexpected end of file syntax error in .bash_profile file
- bash error: ./mac_or_linux.sh: line 19: syntax error: unexpected end of file — Nested ifs
- Why am I getting an unexpected end of file error when running a bash script?
- syntax error near unexpected token `fi’ for bash script that checks for file
- Unexpected end of file error in bash script (Makefile) nested for-loop
- .bashrc error bash: /home/jason/.bashrc: line 115: syntax error: unexpected end of file
- Bash error: «b.sh: line 52: syntax error: unexpected end of file logout»
- Bash syntax error: line 7: unexpected end of file
- Unexpected end of file error in bash
- Unexpected end of file error with every bash script I write
- Syntax error in .bash_profile unexpected end of file
More Query from same tag
- Restart process via Bash
- How to cancel/not execute Bitbucket Pipelines builds based on a condition?
- Is there a way to create key-value pairs in Bash script?
- Understand flag setting
- How can find similarity between sentences?
- Append content to JSON Array (i.e. replacing the last ‘]’ character) with pure Bash without reading the whole line into memory
- Creating a list of all commits from which a branch has been made using bash
- Print only lines different from several strings of a bash script
- Compress .tar.gz without directories in Perl script
- Bash echo and actions order
- Shell script to run jar of any version
- Tell iTunes to open a .m3u playlist file
- Redirect output of script to multiple log files within the script
- Shell script with single choice options
- Matching timestamps from git log with bash regex
- How to detect if a git clone failed in a bash script
- Regular expression to extract everything between two tags
- Removing all HTML tags from a webpage
- Cannot give myself root my permissions
- Configure uwsgi and nginx using Docker
- Saving part of each line to an array in bash
- Find (unix) — routing standard output from multiple -exec primaries to multiple files
- Asterisk: How to convert time to seconds
- Shell script variable expansion with escape
- Storage service API call
- Later chars displaces previous chars in string concat and output
- Copy and Rename script in Bash
- Terminating SSH Session after lock
- Why does this user data script not pull from Git repo?
- What is the purpose of && :; in bash scripts