Синтаксическая ошибка неожиданный конец файла bash

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

I am writing a makefile in bash and I have a target in which I try to find if a file exists and even though I think the syntax is correct, i still gives me an error.

Here is the script that I am trying to run

read: 
        if [ -e testFile] ; then  
        cat testFile 
        fi

I am using tabs so that is not a problem.

The error is (when I type in: «make read»)

if [ -e testFile] ; then 
        cat testFile 
        fi
/bin/sh: Syntax error: end of file unexpected (expecting "fi")
make: *** [read] Error 2

ephemient's user avatar

ephemient

198k38 gold badges279 silver badges391 bronze badges

asked Apr 19, 2009 at 5:48

Jaelebi's user avatar

Try adding a semicolon after cat testFile. For example:

read: 
    if [ -e testFile ] ; then  cat testFile ; fi

alternatively:

read:
    test -r testFile && cat testFile

Julien Roncaglia's user avatar

answered Apr 19, 2009 at 6:01

jwa's user avatar

jwajwa

4914 silver badges3 bronze badges

3

I ran into the same issue. This should do it:

file:
    @if [ -e scripts/python.exe ] ; then 
    echo TRUE ; 
    fi

answered Mar 25, 2011 at 23:39

honkaboy's user avatar

honkaboyhonkaboy

911 silver badge1 bronze badge

Since GNU Make 3.82, you can add .ONESHELL: to the top of the file to tell make to run all the lines within a target in a single shell.

.ONESHELL:
SHELL := /bin/bash

foobar:
    if true
    then
        echo hello there
    fi

See the documentation.

Prepend lines with @ or add the .SILENT: option beneath .ONESHELL: to suppress echoing lines.

answered Apr 2, 2017 at 21:04

Evidlo's user avatar

EvidloEvidlo

1731 silver badge8 bronze badges

0

I also met this problem.

And the reason is that I added some comments after the «».

answered Jul 18, 2010 at 2:38

HackNone's user avatar

HackNoneHackNone

5046 silver badges12 bronze badges

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

Claudio Sabato - Codefather - Software Engineer and Programming Coach

I’m a 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.

Solved "syntax error: unexpected end of File" in Linux Shell Scripting

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 !!

Неожиданный конец файла

Может кто-нибудь объяснить, почему конец файла неожиданно в строке 49? (Строка 49 — одна строка после последней строки)

#!/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

2014-06-19 16:11

4
ответа

Решение

Вы также должны были получить еще одну ошибку, которая может быть более информативной:

/home/terdon/scripts/b.sh: строка 49: предупреждение: здесь-документ в строке 21, разделенный концом файла (требуется `EOF ‘)

/home/terdon/scripts/b.sh: строка 50: синтаксическая ошибка: неожиданный конец файла

Ваша ошибка в том, что перед строкой, заканчивающей heredoc, есть пробелы. Чтобы взять простой пример, это жалуется:

#!/bin/bash 

cat << EOF
   hello
   EOF

Но это не так:

#!/bin/bash 

cat << EOF
   hello
EOF


terdon

19 июн ’14 в 16:20
2014-06-19 16:20

2014-06-19 16:20

Я получил две строки, которые должны помочь вам разобраться, что происходит:

./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

Ваш heredoc (<< EOF) конструкция построена неправильно. Он чувствителен к пробелам, поэтому вы можете либо убрать его обратно:

...
    command <<EOF
        ...
EOF

Или дайте ему знать, что вы вкладываете его (и это должна быть вкладка):

...
    command <<-EOF
        ...
    EOF

Я предпочитаю второе, потому что оно позволяет вам структурировать сценарий намного лучше… Что-то, от чего ваш сценарий уже может извлечь выгоду.


Oli

19 июн ’14 в 16:23
2014-06-19 16:23

2014-06-19 16:23

Предупреждение об окончании файла

%>: строка 49: предупреждение: здесь-документ в строке 21, разделенный концом файла (требуется ‘EOF’)

  • heredoc ищет разделитель (конечный тег), в данном случае EOF
  • он никогда не распознается в вашем примере, потому что он начинается с пробела
  • конец фактического файла достигается без поиска разделителя; отсюда и предупреждение

Эту проблему можно решить, удалив пробелы, или, как Терндон указывает на использование вкладок — я этого не знал


Другой

Другая распространенная ошибка, связанная с ошибкой конца файла, связана с проблемами пробелов. Обычно от копирования онлайн-кода, отформатированного для Windows, и запуска его в Linux.

Это можно решить, запустив dos2unix в файле, чтобы быстро конвертировать эти символы.


Mike

05 апр ’19 в 15:24
2019-04-05 15:24

2019-04-05 15:24

Если вы используете vim или vi, попробуйте использовать команду

:set list

Вы сможете увидеть пробелы между символом $

Иногда бывает полезно выяснить какое-то неожиданное поведение.
В этом случае удалите пробелы закончил работу.


whale

12 июл ’15 в 13:44
2015-07-12 13:44

2015-07-12 13:44

Другие вопросы по тегам
bash

Понравилась статья? Поделить с друзьями:
  • Синтаксическая ошибка неверные параметры not
  • Синтаксическая ошибка нанизывание падежей
  • Синтаксическая ошибка на флешке как исправить
  • Синтаксическая ошибка на телевизоре
  • Синтаксическая ошибка на планшете как исправить