I have a very simple file, «retrieve4.sh»
Here is the full code:
while [ 1 ]
do
nohup php retrieve4.php 1 > /dev/null 2>&1 &
nohup php retrieve4.php 2 > /dev/null 2>&1 &
done
I keep getting the error
Syntax error: end of file unexpected (expecting «do»)
Where am I going wrong?
Alex Andrei
7,2353 gold badges28 silver badges42 bronze badges
asked Jan 12, 2016 at 8:15
5
As per the above comment, you mentioned «I’m editing it on Windows and the server is Linux», the return carriage may be causing the issue.
Try a one-line solution to verify:
while true ; do php retrieve4.php ; done > /dev/null
RJFalconer
10.5k5 gold badges50 silver badges65 bronze badges
answered Nov 20, 2017 at 10:32
If it should be an infinite loop try
while [ 1 = 1 ]
do
nohup php retrieve4.php 1 > /dev/null 2>&1 &
nohup php retrieve4.php 2 > /dev/null 2>&1 &
done
EDIT
while [ 1 ]
do
echo 'test'
done
This is running perfectly well on my setup. Therefore I’d expect your method of running the script is wrong
You could also try something like this:
while true ; do php my_script.php ; done > /dev/null
RJFalconer
10.5k5 gold badges50 silver badges65 bronze badges
answered Jan 12, 2016 at 8:21
FrnakFrnak
6,4315 gold badges36 silver badges66 bronze badges
8
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!
- Статус темы:
-
Закрыта.
-
Помогите пишу в start.sh :
#!/bin/bashBINDIR=$(dirname «$(readlink -fn «$0″)»)
cd «$BINDIR»while true
do
java -Xincgc -Xms1024M -Xmx1024M -jar craftbukkit.jarecho -e ‘If you want to completely stop the server process now, press ctrl-C before thentime is up!’
echo «Rebooting in:»
for i in {5..1}
do
echo «$i…»
sleep 1
done
echo ‘Restarting now!’
и пишет Syntax error: end of file unexpected (expecting «done»)
Помогите исправить ошибку
P.S. Я в этом 0 ) -
почему два «do», echo после done? криво
-
Можешь скинуть готовый вариант плиз
-
Хватит сдуваться!!!
Уйди с говно хостинга(loadvirus) на каждой vps/vds вирус сдувают вас там переходи вот на этот
else
иди играй в казино рулетку европейскую -
Vedroyder и caNek нравится это.
-
#!/bin/bash BINDIR=$(dirname "$(readlink -fn "$0")") cd "$BINDIR" while true do echo 'Restarting now!' java -Xincgc -Xms1024M -Xmx1024M -jar craftbukkit.jar echo -e 'If you want to completely stop the server process now, press ctrl-C before thentime is up!' echo "Rebooting in:" for i in {5..1} # тут был do echo "$i..." sleep 1 done
попробуй так
-
Теперь так) Syntax error: end of file unexpected (expecting «do»)
-
#!/bin/bash BINDIR=$(dirname "$(readlink -fn "$0")") cd "$BINDIR" while true ; do echo 'Restarting now!' java -Xincgc -Xms1024M -Xmx1024M -jar craftbukkit.jar echo -e 'If you want to completely stop the server process now, press ctrl-C before thentime is up!' echo "Rebooting in:" for i in {5..1} echo "$i..." sleep 1; done
точку с запятой забыл
Сникерсни и gasfull нравится это.
-
Syntax error: word unexpected (expecting «do»)
-
методом тыка выяснил что виновата эта строчка for i in {5..1}, непонимаю зачем она нужна?
-
Скинь готовый вариант))плиз
-
все, до меня доепрло
#!/bin/bash BINDIR=$(dirname "$(readlink -fn "$0")") cd "$BINDIR" while true ; do echo 'Restarting now!' java -Xincgc -Xms1024M -Xmx1024M -jar craftbukkit.jar echo -e 'If you want to completely stop the server process now, press ctrl-C before thentime is up!' echo "Rebooting in:" for i in {5..1} do echo "$i..." sleep 1; done done
совсмем невнимательный, у цикла for надо было done написать)
а вот команду запуска я бы поменялjava -Xincgc -Xms512M -Xmx1024M -jar craftbukkit.jar
а то всю память сожрет и отвалится
-
СПАСИБО ТЕБЕ ОГРОМНОЕ!
- Статус темы:
-
Закрыта.
Поделиться этой страницей
Модератор: Модераторы разделов
-
apekoff
- Сообщения: 25
/bin/bash вопрос по while read
Всем привет!
Интересует вопрос по bash
начинаю только изучать
есть скрипт
Код: Выделить всё
#!/bin/bash
list1=/tmp/.list1
list2=/tmp/.list2
cat /etc/some_app/some_conf/* | grep "full_Path" | cut -d """ -f 2 > $list1
cat /etc/some_app/some_conf/* | grep "Name" | cut -d """ -f 2 > $list2
cat $list1 | while read root_dir ;do
echo $root_dir
dirname=$(basename $root_dir)
cat $list2 | while read root_name ;do
echo $root_name
mkdir -p /tmp/data/$root_name/dumps/
touch /tmp/data/$root_name/dumps/$dirname.`date +%Y-%m-%d`.txt
done;
done;
По итогам этого скрипта хочется чтобы в в каждую папку $root_name создавался файлик dumps/$dirname.`date +%Y-%m-%d.txt
А выходит что в каждую папку $root_name создается файлы от всех $dirname
грубо говоря выглядит так —
/tmp/data/alex/dumps/alex.txt
/tmp/data/alex/dumps/jhon.txt
/tmp/data/alex/dumps/david.txt
А нужно чтоб выглядело так —
/tmp/data/alex/dumps/alex.txt
/tmp/data/jhon/dumps/jhon.txt
/tmp/data/david/dumps/david.txt
Спасибо.
-
SLEDopit
- Модератор
- Сообщения: 4814
- Статус: фанат консоли (=
- ОС: GNU/Debian, RHEL
Re: /bin/bash вопрос по while read
Сообщение
SLEDopit » 28.11.2013 17:20
Как всё сложно.
Я не знаю структуру /etc/some_app/some_conf/*
но предположим, что за каждым full_Path идёт ровно один Name ( если это не так, то код неверен )
Код: Выделить всё
grep "full_Path|Name" /etc/some_app/some_conf/* | cut -d """ -f 2 | sed 'N;s/n/ /' | while root_dir rootname ; do
mkdir -p /tmp/data/$root_name/dumps/
touch /tmp/data/$root_name/dumps/$dirname.`date +%Y-%m-%d`.txt
done
UNIX is basically a simple operating system, but you have to be a genius to understand the simplicity. © Dennis Ritchie
The more you believe you don’t do mistakes, the more bugs are in your code.
-
apekoff
- Сообщения: 25
Re: /bin/bash вопрос по while read
Сообщение
apekoff » 28.11.2013 17:56
не получается
Код: Выделить всё
#!/bin/bash
grep "DocumentRoot|ServerName" /etc/apache2/sites-enabled/* | cut -d """ -f 2 | sed 'N;s/n/ /' | while root_dir root_name ; do
mkdir -p /tmp/data/$root_name/dumps/
touch /tmp/data/$root_name/dumps/$dirname.`date +%Y-%m-%d`.txt
done
Код: Выделить всё
scropt.sh: 2: scropt.sh: root_dir: not found
-
SLEDopit
- Модератор
- Сообщения: 4814
- Статус: фанат консоли (=
- ОС: GNU/Debian, RHEL
Re: /bin/bash вопрос по while read
Сообщение
SLEDopit » 28.11.2013 18:34
я слово read пропустил. fixed:
Код: Выделить всё
grep "full_Path|Name" /etc/some_app/some_conf/* | cut -d """ -f 2 | sed 'N;s/n/ /' | while read root_dir rootname ; do
mkdir -p /tmp/data/$root_name/dumps/
touch /tmp/data/$root_name/dumps/$dirname.`date +%Y-%m-%d`.txt
done
UNIX is basically a simple operating system, but you have to be a genius to understand the simplicity. © Dennis Ritchie
The more you believe you don’t do mistakes, the more bugs are in your code.
-
apekoff
- Сообщения: 25
Re: /bin/bash вопрос по while read
Сообщение
apekoff » 28.11.2013 19:01
SLEDopit писал(а): ↑
28.11.2013 18:34
я слово read пропустил. fixed:
Код: Выделить всё
grep "full_Path|Name" /etc/some_app/some_conf/* | cut -d """ -f 2 | sed 'N;s/n/ /' | while read root_dir root_name ; do mkdir -p /tmp/data/$root_name/dumps/ touch /tmp/data/$root_name/dumps/$dirname.`date +%Y-%m-%d`.txt done
эмм работает все!! почти. ., только почему то переопределены root_dir и root_name
Код: Выделить всё
grep "full_Path|Name" /etc/some_app/some_conf/* | cut -d """ -f 2 | sed 'N;s/n/ /' | while read root_dir root_name ; do
mkdir -p /tmp/data/$root_name/dumps/
echo root_dir # ----->>> тут выводится список root_name
touch /tmp/data/$root_name/dumps/$dirname.`date +%Y-%m-%d`.txt
done
Может ли это быть от того что в документах /etc/some_app/some_conf/* «Name» идет раньше чем «full_Path» ?
-
SLEDopit
- Модератор
- Сообщения: 4814
- Статус: фанат консоли (=
- ОС: GNU/Debian, RHEL
Re: /bin/bash вопрос по while read
Сообщение
SLEDopit » 28.11.2013 19:19
apekoff писал(а): ↑
28.11.2013 19:01
Может ли это быть от того что в документах /etc/some_app/some_conf/* «Name» идет раньше чем «full_Path» ?
да, скорее всего. впрочем, вы можете легко в этом убедиться, просто посмотрев файлы. (:
ну и пофиксить, собственно тоже просто: поменять их порядок, там где они читаются ( после read )
UNIX is basically a simple operating system, but you have to be a genius to understand the simplicity. © Dennis Ritchie
The more you believe you don’t do mistakes, the more bugs are in your code.
-
apekoff
- Сообщения: 25
Re: /bin/bash вопрос по while read
Сообщение
apekoff » 29.11.2013 04:04
Код: Выделить всё
#!/bin/bash
grep "Name|Path" /etc/some_app/some_conf/* | cut -d """ -f 2 | sed 'N;s/n/ /' | while read root_name root_dir ; do
dirname=$(basename $root_dir)
mkdir -p /tmp/data/$root_name/dumps/
mkdir -p /tmp/data/$root_name/backups/
cd $root_dir
cd ../
tar pc $dirname --exclude=.git | gzip -5 > /tmp/data/$root_name/backups/$dirname.`date +%Y-%m-%d`.bak.tar.gz
USERNAME='login'
HOSTNAME='ftp.com'
PASSWORD='pass'
ftp -n -i -p $HOSTNAME << EOF
user $USERNAME $PASSWORD
dir
ascii
mkdir $root_name
mkdir $root_name/backups
mkdir $root_name/dumps
put /tmp/data/$root_name/backups/$dirname.`date +%Y-%m-%d`.bak.tar.gz /$root_name/backups/$dirname.`date +%Y-%m-%d`.bak.tar.gz
quit
EOF
exit 0
done
выбивает ошибку scropt.sh: 27: backup.sh: Syntax error: end of file unexpected (expecting «done») почему ?
-
drBatty
- Сообщения: 8735
- Статус: GPG ID: 4DFBD1D6 дом горит, козёл не видит…
- ОС: Slackware-current
- Контактная информация:
Re: /bin/bash вопрос по while read
Сообщение
drBatty » 29.11.2013 05:48
apekoff писал(а): ↑
29.11.2013 04:04
(expecting «done») angry.gifпочему ?
потому-что done пишется после do …, и никак иначе. перед EOF не нужно пробелов, не нужно exit, да ещё и exit 0
-
SLEDopit
- Модератор
- Сообщения: 4814
- Статус: фанат консоли (=
- ОС: GNU/Debian, RHEL
Re: /bin/bash вопрос по while read
Сообщение
SLEDopit » 29.11.2013 13:59
apekoff писал(а): ↑
29.11.2013 04:04
mkdir -p /tmp/data/$root_name/dumps/
mkdir -p /tmp/data/$root_name/backups/
можно написать просто mkdir -p /tmp/data/$root_name/dumps/ /tmp/data/$root_name/backups/
apekoff писал(а): ↑
29.11.2013 04:04
cd $root_dir
cd ../
можно написать просто cd $root_dir/../
apekoff писал(а): ↑
29.11.2013 04:04
ftp -n -i -p $HOSTNAME << EOF
user $USERNAME $PASSWORD
dir
ascii
mkdir $root_name
mkdir $root_name/backups
mkdir $root_name/dumps
put /tmp/data/$root_name/backups/$dirname.`date +%Y-%m-%d`.bak.tar.gz /$root_name/backups/$dirname.`date +%Y-%m-%d`.bak.tar.gz
quit
EOF
Либо убрать все символы перед EOF в конце, либо между << EOF поставить — : <<-EOF . Тогда перед EOF в конце можно использовать табуляцию.
Ну и как заметил drBatty, exit лишний.
А done он у вас просит, потому что пробелы перед EOF. И шелл считает, что то, что нужно скормить ftp ещё не закончилось. Если это исправить, скрипт нормально заработает.
UNIX is basically a simple operating system, but you have to be a genius to understand the simplicity. © Dennis Ritchie
The more you believe you don’t do mistakes, the more bugs are in your code.
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 !!