Синтаксическая ошибка неожиданный конец файла 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

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!

I am trying to create an spritz app. Everything was working fine, but since yesterday I keep getting this error:

./spritz: line 176: syntax error: unexpected end of file

I have checked the script file and everything seems perfect. I am confused, I have an if statement at last and it looks correct! Here is the last portion:

#checks if speed is 150
157 if [[ $2 -eq 150 ]];
158 then
159 starttime=$SECONDS
160      FS=$'\n'
161      for j in `grep --color=always -iP '\b[^aeiou\s]*[aeiou][^aeiou\s]*\K[aeiou]' $1`;
162      do
163            #Reads the text file in the centre of the screen
164            echo "                                                    ___________________"
165            echo "                                                             $j";
166            echo "                                                    ___________________"
167            echo "                                                                               Speed 150 wpm"
168            sleep  0.9;
169            clear;
170       done
171 endtime=$(($SECONDS - $starttime))
172            echo "You read $words_read words in $endtime seconds!"
173       exit 8
174 fi

What could cause that error?

Jeff Schaller's user avatar

Jeff Schaller

66.3k35 gold badges114 silver badges250 bronze badges

asked Mar 29, 2015 at 1:31

Scott Pearce's user avatar

5

The diagnostic «unexpected end of file» is a hint that you have some unmatched or unterminated opening syntactical construct (if w/o fi, do w/o done, opening brackets w/o the associated closing one, opening but unterminated quotes, etc.). The line number pointing to the end of the script is not helpful in this case, beyond saying to inspect your syntactical constructs; the error may be anywhere in your code. You have to check that.

answered Mar 29, 2015 at 4:15

Janis's user avatar

JanisJanis

14k3 gold badges26 silver badges42 bronze badges

2

Not the answer you’re looking for? Browse other questions tagged

.

#!/bin/bash
ocpath='/var/www/nextcloud'
htuser='www-data'
htgroup='www-data'
rootuser='root'

printf "Creating possible missing Directories\n" 
mkdir -p $ocpath/data 
mkdir -p $ocpath/assets 
mkdir -p $ocpath/updater 

printf "chmod Files and Directories\n" 
find ${ocpath}/ -type f -print0 | xargs -0 chmod 0640 
find ${ocpath}/ -type d -print0 | xargs -0 chmod 0750 

printf "chown Directories\n" 
chown -R ${rootuser}:${htgroup} ${ocpath}/ 
chown -R ${htuser}:${htgroup} ${ocpath}/apps/ 
chown -R ${htuser}:${htgroup} ${ocpath}/assets/ 
chown -R ${htuser}:${htgroup} ${ocpath}/config/ 
chown -R ${htuser}:${htgroup} ${ocpath}/data/ 
chown -R ${htuser}:${htgroup} ${ocpath}/themes/ 
chown -R ${htuser}:${htgroup} ${ocpath}/updater/ 

chmod +x ${ocpath}/occ 

printf "chmod/chown .htaccess\n" 

if [ -f ${ocpath}/.htaccess ] 
	then 
		chmod 0644 ${ocpath}/.htaccess 
		chown ${rootuser}:${htgroup} ${ocpath}/.htaccess 
	fi 
if [ -f ${ocpath}/data/.htaccess ] 
	then 
		chmod 0644 ${ocpath}/data/.htaccess 
		chown ${rootuser}:${htgroup} ${ocpath}/data/.htaccess 
fi

собственно я в баше вообще 0 , даже не знаю с чем его едят , мне просто нужно выполнить файл , а он падло ругается )) , гуглил говорят ошибка чаще всего бывает потому что не закрыт if тегом fi , но у меня походу не тот случай , как решить проблему?

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

Может кто-нибудь объяснить, почему конец файла неожиданно в строке 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

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