I am making this code for a minecraft server plugin updater
I am a new shell scripter so I don’t know alot…
when I run this code I get a error:
#!/bin/sh
export PATH=$PATH:.
#Options
PLUGINDOWNLOADLINK=http://api.bukget.org/3/plugins/bukkit/$PLUGINNAME/latest/download
# Plugin folder
if [ -f $PWDplugins ]; then
PLUG=$PWDplugins
else
PLUG=$PWDplug-ins
fi
cd $PLUG
if [ ! -f .update ]; then
mkdir update
echo Making Directory "update"..
fi
# Plugins Found
for i in $( ls );
do
PLUGINNAME=$i
done
cd .update
wget $PLUGINDOWNLOADLINK
# No Plugins Found
if [ ! -f $PLUG ]; then
echo
echo
echo No plugin found.
echo
echo
echo
echo Plugins can be downloaded here:
echo http://dev.bukkit.org/bukkit-plugins
fi
# stop
sleep 3s
exit
I get this error:
Syntax error: end of file unexpected (expecting "then")
so I put «then» in the place it wanted me to and ran it again:
it gave me this error now:
Syntax error: end of file unexpected
I wrote it on windows 7 notepad++
how can I fix this?
asked Aug 9, 2013 at 21:22
user2649805user2649805
2831 gold badge3 silver badges7 bronze badges
4
I have met the same problem. And the problem is the format of the file is «dos», but in linux shell requires «unix», so I install the «dos2unix»
$ sudo apt-get install dos2unix
or if you use emacs, you can do this:
C-x RET f unix
Good luck
answered Sep 1, 2013 at 1:23
Ni XiaoniNi Xiaoni
1,6192 gold badges13 silver badges10 bronze badges
0
- The Unix directory separator is forward slash not backslash.
- Does your editor on windows have an option to save files in «Unix» file format? The shell is seeing the word
then^M
with a carriage return on the end. If you don’t have dos2unix then try running this command:sed -i 's/r$//' filename
answered Aug 9, 2013 at 23:47
glenn jackmanglenn jackman
234k37 gold badges217 silver badges342 bronze badges
It’s because of file formatting. I faced the same problem. Just create another file with (.sh) extensions using gedit. Then paste the code into the new document. Hope this will resolve the issue.
gedit file-name.sh
answered Jun 1, 2019 at 7:56
1
- Печать
Страницы: [1] 2 Все Вниз
Тема: Помогите со скриптом (Прочитано 6431 раз)
0 Пользователей и 1 Гость просматривают эту тему.

Alexx_b
Только начал разбираться с написанием скриптов в linux и сразу получил проблему, которую не могу решить.
Пробую выполнить простейший скрипт:
#!/bin/bash
на что мне выводиться следующее сообщение:
if ["foo"="foo"]; then
echo Equals
fi
syntax error end of file unexpected (expecting «then»)
почему так?

ArcFi
arcfi@arcfi-laptop:~$ if [ "foo"="foo" ]; then echo Equals; fi
Equals
ps
Пробелы.

Alexx_b
так у меня тоже работает, но дело в том, что надо все это из файла запускать, т.е. у меня файл называется 123, я набираю команду sh 123 и получаю это ошибку. В строчку — тоже пробовал писать — не прокатывает
plin2s
« Последнее редактирование: 15 Апреля 2009, 10:11:42 от plin2s »

Alexx_b
Пробовал я и так:
#!/bin/bash
все равно не прокатывает.
if [ "foo" = "foo" ];
then
echo Equals;
fi
Может у меня какого-нить пакета не хватает?
Пользователь решил продолжить мысль 15 Апреля 2009, 10:14:49:
за ссылку — спасибо!
Но сам я взял данный пример из статьи по BASH программированию, а не сам придумал, вот и спрашиваю почему у меня не работает даже такая несложная штука
« Последнее редактирование: 15 Апреля 2009, 10:14:49 от Alexx_b »
plin2s
#!/bin/bash
if [ "foo" = "foo" ]
then echo Equals
fi

ArcFi
echo -e '#!/bin/bashnnif [ "foo"=="foo" ]nthenntecho Equalsnfi' > script-00.sh && chmod +x script-00.sh && ./script-00.sh

Alexx_b
#!/bin/bash
if [ "foo" = "foo" ]
then echo Equals
fi
Спасибо!
Вот именно так — работает…
Однако, чувствую не просто будет разобраться с BASH, при таком чувствительном отношении к пробелам, переносам строкии ;
Пользователь решил продолжить мысль 15 Апреля 2009, 08:25:00:
echo -e '#!/bin/bash
if [ "foo"=="foo" ]
then
echo Equals
fi' > script-00.sh && chmod +x script-00.sh && ./script-00.sh
Спасибо, конечно, но пока это слишком сложно для моего понимания… только начал разбираться с программированием в linux, а использовать то, чего не понимаю, не люблю…
Пользователь решил продолжить мысль 15 Апреля 2009, 10:37:05:
Ещё один вопрос — пытаюсь использовать переменные, пишу так:
#!/bin/bash
вылетает ошибка:
FOLDER=/home/user/lfolder/1
if [ $(stat -c %s $FOLDER) = $(stat -c %s $FOLDER) ]
then echo Equals
else echo NON
fi
stat: cannot stat ‘/home/user/lfolder/1r’: No such file or directory
Откуда берется r? И как следует использовать переменную в данном случае?
Причем, если вместо переменной писать реальный путь, то все работает.
« Последнее редактирование: 15 Апреля 2009, 10:37:05 от Alexx_b »

Sova777
С переносами всё нормально. Это тоже правильный код:
#!/bin/bash
if [ "foo"="foo" ]; then
echo Equals
fi
>if [ $(stat -c %s $FOLDER) = $(stat -c %s $FOLDER) ]
Это какой-то башизм? В классическом шеле пишут так:
STAT_VALUE=`stat -c %s $FOLDER`
« Последнее редактирование: 15 Апреля 2009, 11:11:23 от Sova777 »
Пользователь OpenSolaris 2008.11, Ubuntu 8.10, Windows XP. Mac OS X не нравится, стараюсь не использовать.

Alexx_b
написал вот так:
#!/bin/bash
все равно таже ошибка, т.е. в конец адреса добавляется r
FOLDER=$HOME/lfolder/1
ST=`stat -c %s $FOLDER`
if [ $ST = $ST ]
then echo 1
else echo 2
fi

Sova777
странно, а так:
#!/bin/bash
FOLDER=$HOME/lfolder/1
ST=`stat -c %s $FOLDER`
if [ "$ST" = "$ST" ]
then echo 1
else echo 2
fi
r — виндовый перевод строки. Подумай, может ты редактировал файл в Windows?
« Последнее редактирование: 15 Апреля 2009, 11:45:48 от Sova777 »
Пользователь OpenSolaris 2008.11, Ubuntu 8.10, Windows XP. Mac OS X не нравится, стараюсь не использовать.

Alexx_b
так тоже не прокатывает, т.е. путь подставляется правильно, но добавляется ещё r в конец и получается вот так:
stat ‘/home/user/lfolder/1r’

Sova777
Запусти такую комманду:
od -c <имя скрипта>
Что видно?
« Последнее редактирование: 15 Апреля 2009, 11:55:31 от Sova777 »
Пользователь OpenSolaris 2008.11, Ubuntu 8.10, Windows XP. Mac OS X не нравится, стараюсь не использовать.

Rosik
проясню некоторые вопросы с пробелами:
синтаксис оператора if уже приводили, но без пояснений.
код в общем случае выглядит как
if cmd1; then cmd2; fi;
здесь cmd1 это некоторая программа, которая делает return 0; либо return -1; (c++). если программа сделала return 0 то скрипт переходит к cmd2.
Теперь про квадратные скобки. Это ни что иное как альтернатива программе test (читай man test) отсюда и проблема с пробелами.
if [ "foo" = "foo" ]
Просто программа test хочет видеть 3 аргумента, а когда мы пишем test «boo»=»boo» она видит только 1 ( аргументы разделяются пробелами ), и мы получаем ошибку
эквивалентно
if test "foo" = "foo"
Со вторым скриптом не знаю, но двойные кавычки » не помешают. (с кавычками там вообще много веселья)
ЗЫ я когда-то читал http://www.opennet.ru/docs/RUS/bash_scripting_guide/ вроде ниче так.

Alexx_b
Запусти такую комманду:
od -c <имя скрипта>
Что видно?
вот что получается
alexx@serveru:~/lfolder$ od -c 1
0000000 # ! / b i n / b a s h r n F O L
0000020 D E R = $ H O M E / l f o l d e
0000040 r / 1 r n S T = ` s t a t — c
0000060 % s $ F O L D E R ` r n i f
0000100 [ » $ S T » = » $ S T
0000120 » ] r n t h e n e c h o 1
0000140 r n e l s e e c h o 2 r n f
0000160 i
0000161
alexx@serveru:~/lfolder$
Пользователь решил продолжить мысль 15 Апреля 2009, 08:58:28:
Rosik, спасибо за пояснения, стало чуть яснее.
« Последнее редактирование: 15 Апреля 2009, 13:04:30 от Alexx_b »
- Печать
Страницы: [1] 2 Все Вверх
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!
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[^aeious]*[aeiou][^aeious]*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♦
65.2k34 gold badges106 silver badges240 bronze badges
asked Mar 29, 2015 at 1:31
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
JanisJanis
13.7k2 gold badges24 silver badges41 bronze badges
2
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 !!
fedya.lutkovski 3 / 3 / 1 Регистрация: 24.03.2012 Сообщений: 174 |
||||
1 |
||||
11.05.2017, 11:31. Показов 6970. Ответов 6 Метки нет (Все метки)
Помогите разобраться, в чем ошибка
__________________
0 |
nezabudka 2898 / 736 / 246 Регистрация: 28.06.2015 Сообщений: 1,515 Записей в блоге: 16 |
||||||||
11.05.2017, 15:22 |
2 |
|||||||
В 5 строчке нет завершения как в предыдущей
Добавлено через 8 минут
0 |
3 / 3 / 1 Регистрация: 24.03.2012 Сообщений: 174 |
|
11.05.2017, 15:23 [ТС] |
3 |
а Вы прокрутить сообщение пробовали?
0 |
2898 / 736 / 246 Регистрация: 28.06.2015 Сообщений: 1,515 Записей в блоге: 16 |
|
11.05.2017, 15:37 |
4 |
fedya.lutkovski, Пробовала но поздно. Сори
0 |
3 / 3 / 1 Регистрация: 24.03.2012 Сообщений: 174 |
|
11.05.2017, 15:56 [ТС] |
5 |
Что-то пошло не так)
0 |
Модератор 2792 / 2035 / 682 Регистрация: 02.03.2015 Сообщений: 6,509 |
|
11.05.2017, 15:57 |
6 |
а Вы прокрутить сообщение пробовали? А писать надо по стандарту, а не как левая нога захотела…
0 |
3 / 3 / 1 Регистрация: 24.03.2012 Сообщений: 174 |
|
11.05.2017, 16:04 [ТС] |
7 |
Вот что пишет консолька Миниатюры
0 |
IT_Exp Эксперт 87844 / 49110 / 22898 Регистрация: 17.06.2006 Сообщений: 92,604 |
11.05.2017, 16:04 |
Помогаю со студенческими работами здесь Не объявляется массив, выдаёт ошибку: Syntax error: «(» unexpected
Для любого целого k обозначим количество цифр… Parse error: syntax error, unexpected end of file, expecting function (T_FUNCTION) ошибка » syntax error, unexpected end of file in» Искать еще темы с ответами Или воспользуйтесь поиском по форуму: 7 |
No rule to make target | |
GNUmakefile:1: *** missing separator. Stop. | |
Syntax error : end of file unexpected (expecting «fi») | |
OLDPWD not set | |
@echo: command not found | |
-bash: make: command not found | |
Похожие статьи |
No rule to make target
make: *** No rule to make target ‘main.cpp’, needed by ‘main.o’. Stop.
GNUmakefile:1: *** missing separator. Stop.
Если вы видите ошибку
GNUmakefile:1: *** missing separator. Stop.
Обратите внимание на GNUmakefile:1:
1 — это номер строки, в которой произошла ошибка
Возможно где-то вместо табуляции затесался пробел. Напоминаю, что в makefile отступы должны быть заданы табуляциями.
Либо таргет перечислен без двоеточия .PHONY clean вместо .PHONY: clean
Либо какая-то похожая ошибка.
Syntax error : end of file unexpected (expecting «fi»)
Если вы видите ошибку
Syntax error : end of file unexpected (expecting «fi»)
Обратите внимание на расстановку ; в конце выражений и расстановку при переносе строк.
Изучите этот
пример
и сравните со своим кодом.
OLDPWD not set
Если внутри makefile вы выполняете cd и видите ошибку
OLDPWD not set
Попробуйте сперва явно перейти в текущую директорию с помощью
CURDIR
cd $(CURDIR)
@echo: command not found
Если внутри makefile вы пытаетесь подавить вывод echo и получаете
@echo: command not found
Скорее всего echo это не первая команда в строке
НЕПРАВИЛЬНО:
if [ ! -f /home/andrei/Downloads/iso/centos_netinstall.iso ]; then
rm ./CentOS-7-x86_64-NetInstall-*;
wget -r -np «http://builder.hel.fi.ssh.com/privx-builds/latest/PrivX-master/Deliverables/» -A «CentOS-7-x86_64-NetInstall-2009.iso
-*.iso;
else
@echo «WARNING: centos_netinstall.iso already exists»;
ПРАВИЛЬНО:
@if [ ! -f /home/andrei/Downloads/iso/centos_netinstall.iso ]; then
rm ./CentOS-7-x86_64-NetInstall-*;
wget -r -np «http://builder.hel.fi.ssh.com/privx-builds/latest/PrivX-master/Deliverables/» -A «CentOS-7-x86_64-NetInstall-2009.iso
-*.iso;
else
echo «WARNING: centos_netinstall.iso already exists»;
-bash: make: command not found
Ошибка
-bash: make: command not found
Означает, что make не установлен.
Установить make в rpm системах можно с помощью yum в deb система — с помощью apt
sudo yum -y install make
sudo apt -y install make
make | |
Основы make | |
PHONY | |
CURDIR | |
shell | |
wget + make | |
Переменные в Make файлах | |
ifeq: Условные операторы | |
filter | |
-c: Компиляция | |
Linux | |
Bash | |
C | |
C++ | |
C++ Header файлы | |
Configure make install | |
DevOps | |
Docker | |
OpenBSD | |
Errors make |