Bin sh 1 syntax error end of file unexpected expecting 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 ...

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

195k38 gold badges279 silver badges389 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

4814 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

1641 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

Edit: Note that the original post has been edited since this answer was written and has been reformatted. You should look at the history to see the original formatting to understand the context for this answer.

This error occurs often when you have mismatched structure — that is, you do not have matching double quotes, matching single quotes, have not closed a control structure such as a missing fi with an if, or a missing done with a for.

The best way to spot these is to use correct indentation, which will show you where you have a broken control structure, and syntax highlighting, which will show you where quotes are not matched.

In this particular case, I can see you are missing a fi. In the latter part of your code, you have 5 ifs and 4 fis. However you also have a number of other problems — your backquoted touch /tmp/alert.txt... command is syntactically invalid, and you need a space before the closing bracket of an if test.

Clean up your code, and errors start to stand out.

  • Печать

Страницы: [1] 2  Все   Вниз

Тема: Помогите со скриптом  (Прочитано 6397 раз)

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
FOLDER=$HOME/lfolder/1
ST=`stat -c %s $FOLDER`
if  [ $ST = $ST ]
then echo 1
else echo 2
fi
все равно таже ошибка, т.е. в конец адреса добавляется r :(


Оффлайн
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" ]
эквивалентно
if test "foo" = "foo"
Просто программа test хочет видеть 3 аргумента, а когда мы пишем test «boo»=»boo» она видит только 1 ( аргументы разделяются пробелами ), и мы получаем ошибку

Со вторым скриптом не знаю, но двойные кавычки » не помешают. (с кавычками там вообще много веселья)

ЗЫ я когда-то читал 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  Все   Вверх

fedya.lutkovski

3 / 3 / 1

Регистрация: 24.03.2012

Сообщений: 174

1

11.05.2017, 11:31. Показов 6884. Ответов 6

Метки нет (Все метки)


Помогите разобраться, в чем ошибка
Скрипт брал тут http://blog.angel2s2.ru/2016/0… 2555986313
Сам скрипт

Bash
1
2
3
4
5
6
7
8
9
10
#!/bin/bash
TOKEN=''
which curl &>/dev/null
if [ $? -ne 0 ] ; then echo 'FAIL: curl not found.' && exit 1 ; fi
if [ $# -ne 3 ] ; then echo 'FAIL: Params not defined.' && echo 'Usage: zabbix-to-telegram-notify.sh TelegramID Subject Message' && exit 1 ; fi
CHAT_ID="$1"
SUBJECT="$2"
MESSAGE="$3"
curl -s --header 'Content-Type: application/json' --request 'POST' --data "{"chat_id":"${CHAT_ID}","text":"${SUBJECT}n${MESSAGE}"}" "https://api.telegram.org/bot${TOKEN}/sendMessage" | grep -q '"ok":false,'
if [ $? -eq 0 ] ; then exit 1 ; fi

__________________
Помощь в написании контрольных, курсовых и дипломных работ, диссертаций здесь



0



nezabudka

Эксперт NIX

2898 / 736 / 246

Регистрация: 28.06.2015

Сообщений: 1,515

Записей в блоге: 16

11.05.2017, 15:22

2

В 5 строчке нет завершения как в предыдущей

Bash
1
;fi

Добавлено через 8 минут
А скорее всего так

Bash
1
&& exit 1 ; fi



0



3 / 3 / 1

Регистрация: 24.03.2012

Сообщений: 174

11.05.2017, 15:23

 [ТС]

3

а Вы прокрутить сообщение пробовали?



0



Эксперт NIX

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



Модератор

Эксперт NIX

2792 / 2035 / 682

Регистрация: 02.03.2015

Сообщений: 6,509

11.05.2017, 15:57

6

Цитата
Сообщение от fedya.lutkovski
Посмотреть сообщение

а Вы прокрутить сообщение пробовали?

А писать надо по стандарту, а не как левая нога захотела…
Приведенный код работает. Проблема может быть в виндовых переводах строк: уберите символы <возврат_каретки>(r)



0



3 / 3 / 1

Регистрация: 24.03.2012

Сообщений: 174

11.05.2017, 16:04

 [ТС]

7

Вот что пишет консолька

Миниатюры

Syntax error: end of file unexpected (expecting "fi")
 



0



IT_Exp

Эксперт

87844 / 49110 / 22898

Регистрация: 17.06.2006

Сообщений: 92,604

11.05.2017, 16:04

Помогаю со студенческими работами здесь

Не объявляется массив, выдаёт ошибку: Syntax error: «(» unexpected
Делаю всё по мануалам, точно как написано, но не работает, и всё тут.
Пишу так:
arr=(1 2 3)…

Ошибка: syntax error, unexpected end of file, expecting end
ДВ! Помогите пожалуйста . нужно решение в Scilab.

Для любого целого k обозначим количество цифр…

Parse error: syntax error, unexpected end of file, expecting function (T_FUNCTION)
Выскакивает такая ошибка &quot;Parse error: syntax error, unexpected end of file, expecting function…

ошибка » syntax error, unexpected end of file in»
Доброго времени суток, при выполнении код выдает ошибку &quot; syntax error, unexpected end of file in&quot;,…

Искать еще темы с ответами

Или воспользуйтесь поиском по форуму:

7

  • Home
  • Forum
  • The Ubuntu Forum Community
  • Ubuntu Official Flavours Support
  • General Help
  • [SOLVED] bash — expecting «fi» but it is already there

  1. bash — expecting «fi» but it is already there

    I’ve wrote a little bash script to ease the installation of programs which are not part of the standard installation of ubuntu:

    Code:

    #! /bin/bash
    #installing ubuntu-restricted-extras vlc, SUN Java, handbrake, bumblebee (hybrid graphics management tool), skype, pidgin, Thunderbird 
    echo ""
    echo ""
    echo "Willkommen bei der Installationsroutine fuer das Asus X5MSN"
    echo "------------------------------------------------------------"
    echo ""
    if [ "$(whoami)" != "root" ]; 
    then 
        echo "Das Script muss mit root-Rechten ausgefuehrt werden!"
        echo "Nutze: 'sudo ./script.sh'"
        echo ""
    else
    echo "Installation der Ubuntu-Restricted-Extras ..."
    apt-get -y install ubuntu-restricted-extras
    echo "done"
    sleep 5
    echo "Installation des VLC-Players ..."
    echo "--------------------------------"
    apt-get -y install vlc vlc-data  
    echo "done"
    sleep 5
    echo "Hinzufuegen der PPA: Paketquellen fuer SUN JAVA, Handbrake und bumblebee ..."
    echo "---------------------------------------------------------------------------"
    add-apt-repository ppa:ferramroberto/java 
    add-apt-repository ppa:stebbins/handbrake-releases
    add-apt-repository ppa:mj-casalogic/bumblebee
    cp /etc/apt/sources.list /etc/apt/sources.list.bak 
    sh -c 'echo "deb http://archive.canonical.com/ubuntu natty partner" >> /etc/apt/sources.list' 
    sh -c 'echo "deb-src http://archive.canonical.com/ubuntu natty partner" >> /etc/apt/sources.list' 
    apt-get update
    echo "done"
    sleep 5
    echo "Installation von SUN JAVA Runetime Enviroment..."
    echo "------------------------------------------------"
    apt-get -y install sun-java6-jre sun-java6-plugin sun-java6-fonts
    echo "done"
    sleep 5
    echo "Sun Java als Standard-JAVA festlegen"
    echo "------------------------------------"
    update-alternatives --config java
    sleep 5
    echo "Installation von Handbrake ..."
    echo "------------------------------"
    apt-get -y install handbrake
    echo "done"
    sleep 5
    echo "Installation und Konfiguration von bumblebee (fuer Hybrid Graphics INTEL/nVidia) ..."
    echo "-----------------------------------------------------------------------------------"
    apt-get -y install bumblebee
    echo "done"
    sleep 5
    echo "Installation von Thunderbird mit de-language-pack"
    echo "-------------------------------------------------"
    apt-get -y install thunderbird thunderbird-locale-de
    echo "done"
    sleep 5
    echo "Installation von Skype (Colsed Source) ..."
    echo "------------------------------------------"
    apt-get -y install skype
    echo "done"
    sleep 5
    echo "Installation von Pidgin ..."
    echo "---------------------------"
    apt-get -y install pidgin
    echo "done"
    fi 
    exit 0

    The problem is that I get this message:

    (line where you can find «fi»): Syntax error: end of file unexpected (expecting «fi»).

    Where’s the mistake?


  2. Re: bash — expecting «fi» but it is already there

    I’m not sure but I dont like the semicolon at the end of the if statement (after the square brackets). Try removing that and see what happens.

    Failing that comment out all the lins in the else clause and uncomment them one by one. But I think it’s something to do with the semicolon.

    Andrew


  3. Re: bash — expecting «fi» but it is already there

    Quote Originally Posted by apmcd47
    View Post

    I’m not sure but I dont like the semicolon at the end of the if statement (after the square brackets). Try removing that and see what happens.

    Failing that comment out all the lins in the else clause and uncomment them one by one. But I think it’s something to do with the semicolon.

    Andrew

    By comparing the script to one of my own, i would also try to remove the semi-colon.


  4. Re: bash — expecting «fi» but it is already there

    I removed the semicolon but nothing chnaged. If I replace all the code between else and fi by the simple line echo «You are root!» the if condition works fine.


  5. Re: bash — expecting «fi» but it is already there

    Try adding a semicolon after each command between else and fi.


  6. Re: bash — expecting «fi» but it is already there

    No effect, same error report like without the semicolon after each command


  7. Re: bash — expecting «fi» but it is already there

    Try using a function. All those sleep calls might cause issues, or if one of the apt-get requests fails, the if will fail:

    Change:

    Code:

    if [ "$(whoami)" != "root" ]; 
    then 
        echo "Das Script muss mit root-Rechten ausgefuehrt werden!"
        echo "Nutze: 'sudo ./script.sh'"
        echo ""
    else
    echo "Installation der Ubuntu-Restricted-Extras ..."
    apt-get -y install ubuntu-restricted-extras
    echo "done"
    sleep 5
    echo "Installation des VLC-Players ..."
    echo "--------------------------------"
    apt-get -y install vlc vlc-data  
    echo "done"
    sleep 5
    echo "Hinzufuegen der PPA: Paketquellen fuer SUN JAVA, Handbrake und bumblebee ..."
    echo "---------------------------------------------------------------------------"
    add-apt-repository ppa:ferramroberto/java 
    add-apt-repository ppa:stebbins/handbrake-releases
    add-apt-repository ppa:mj-casalogic/bumblebee
    cp /etc/apt/sources.list /etc/apt/sources.list.bak 
    sh -c 'echo "deb http://archive.canonical.com/ubuntu natty partner" >> /etc/apt/sources.list' 
    sh -c 'echo "deb-src http://archive.canonical.com/ubuntu natty partner" >> /etc/apt/sources.list' 
    apt-get update
    echo "done"
    sleep 5
    echo "Installation von SUN JAVA Runetime Enviroment..."
    echo "------------------------------------------------"
    apt-get -y install sun-java6-jre sun-java6-plugin sun-java6-fonts
    echo "done"
    sleep 5
    echo "Sun Java als Standard-JAVA festlegen"
    echo "------------------------------------"
    update-alternatives --config java
    sleep 5
    echo "Installation von Handbrake ..."
    echo "------------------------------"
    apt-get -y install handbrake
    echo "done"
    sleep 5
    echo "Installation und Konfiguration von bumblebee (fuer Hybrid Graphics INTEL/nVidia) ..."
    echo "-----------------------------------------------------------------------------------"
    apt-get -y install bumblebee
    echo "done"
    sleep 5
    echo "Installation von Thunderbird mit de-language-pack"
    echo "-------------------------------------------------"
    apt-get -y install thunderbird thunderbird-locale-de
    echo "done"
    sleep 5
    echo "Installation von Skype (Colsed Source) ..."
    echo "------------------------------------------"
    apt-get -y install skype
    echo "done"
    sleep 5
    echo "Installation von Pidgin ..."
    echo "---------------------------"
    apt-get -y install pidgin
    echo "done"
    fi 
    exit 0

    TO:

    Code:

    function install_procedure(){
    
    echo "Installation der Ubuntu-Restricted-Extras ..."
    apt-get -y install ubuntu-restricted-extras
    echo "done"
    sleep 5
    echo "Installation des VLC-Players ..."
    echo "--------------------------------"
    apt-get -y install vlc vlc-data  
    echo "done"
    sleep 5
    echo "Hinzufuegen der PPA: Paketquellen fuer SUN JAVA, Handbrake und bumblebee ..."
    echo "---------------------------------------------------------------------------"
    add-apt-repository ppa:ferramroberto/java 
    add-apt-repository ppa:stebbins/handbrake-releases
    add-apt-repository ppa:mj-casalogic/bumblebee
    cp /etc/apt/sources.list /etc/apt/sources.list.bak 
    sh -c 'echo "deb http://archive.canonical.com/ubuntu natty partner" >> /etc/apt/sources.list' 
    sh -c 'echo "deb-src http://archive.canonical.com/ubuntu natty partner" >> /etc/apt/sources.list' 
    apt-get update
    echo "done"
    sleep 5
    echo "Installation von SUN JAVA Runetime Enviroment..."
    echo "------------------------------------------------"
    apt-get -y install sun-java6-jre sun-java6-plugin sun-java6-fonts
    echo "done"
    sleep 5
    echo "Sun Java als Standard-JAVA festlegen"
    echo "------------------------------------"
    update-alternatives --config java
    sleep 5
    echo "Installation von Handbrake ..."
    echo "------------------------------"
    apt-get -y install handbrake
    echo "done"
    sleep 5
    echo "Installation und Konfiguration von bumblebee (fuer Hybrid Graphics INTEL/nVidia) ..."
    echo "-----------------------------------------------------------------------------------"
    apt-get -y install bumblebee
    echo "done"
    sleep 5
    echo "Installation von Thunderbird mit de-language-pack"
    echo "-------------------------------------------------"
    apt-get -y install thunderbird thunderbird-locale-de
    echo "done"
    sleep 5
    echo "Installation von Skype (Colsed Source) ..."
    echo "------------------------------------------"
    apt-get -y install skype
    echo "done"
    sleep 5
    echo "Installation von Pidgin ..."
    echo "---------------------------"
    apt-get -y install pidgin
    echo "done"
    }
    
    
    if [ "$(whoami)" != "root" ] 
    then 
        echo "Das Script muss mit root-Rechten ausgefuehrt werden!"
        echo "Nutze: 'sudo ./script.sh'"
        echo ""
    else
    install_procedure
    fi 
    exit 0

    Oh yea, another thing. May be trivial, but its a rule: BASH FILES MUST HAVE ATLEAST A SINGLE EMPTY LINE FOLLOWING THE LAST LINE OF CODE. You have no idea how many times this screwed me over before I started using geany for coding scripts…

    Last edited by zero2xiii; September 4th, 2011 at 12:14 PM.

    Reason: just tought of another thing


  8. Re: bash — expecting «fi» but it is already there

    try chancingwithalso make sure the 1st line is #!/bin/bash not #! /bin/bash

    edit: never mind i niticed you have already an «else» statement.

    bash -v (what version r u using?)
    try to run the comman in dash (#!/bin/dash)

    Last edited by fdrake; September 4th, 2011 at 12:34 PM.

    blog
    Donations BTC : 12FwoB7uAM5FnweykpR1AEEDVFaTLTYFkS
    DOUBLEPLUSGOOD!!


  9. Re: bash — expecting «fi» but it is already there

    @ zero2xiii

    install_routine_asus.sh: 1: Syntax error: «(» unexpected

    @ fdrake
    install_routine_asus.sh: 14 (else-line): Syntax error: «;» unexpected


  10. Re: bash — expecting «fi» but it is already there

    Please upload the file so we can view the EXACT line syntax and compare that to the results you are having.

    The unexpected ( in line 1, is completely wrong. I guess you didn’t read through what I wrote. That is NOT the complete file, only the part you need to change.


Bookmarks

Bookmarks


Posting Permissions

I am getting an error when using sh, but not bash. Any idea why?

$ sh test.sh
test.sh: 5: test.sh: Syntax error: "(" unexpected (expecting "fi")


#!/bin/bash

if [ 1 -eq 1 ]
    then
    declare -a methods=(Method1 Method2 Method3)
    for i in "${methods[@]}"
       do
          echo $i
      done
    else
      echo not found
fi

asked Sep 3, 2021 at 14:24

SEU's user avatar

1

You have a bash hashbang and are running the script with sh. POSIX sh does not support arrays, and while they will still work on some systems there is no guarantee of such, hence the error about the parenthesis.

Use bash test.sh or just make it executable and let the hashbang decide the interpreter.

Also 1 will always equal 1 so your whole if construct is unnecessary.

answered Sep 3, 2021 at 14:34

jesse_b's user avatar

jesse_bjesse_b

34.7k10 gold badges87 silver badges136 bronze badges

1

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!

Я пишу make-файл в bash, и у меня есть цель, в которой я пытаюсь определить, существует ли файл, и хотя я думаю, что синтаксис правильный, я все равно выдает ошибку.

Вот сценарий, который я пытаюсь запустить

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

Я использую вкладки, поэтому это не проблема.

Ошибка (когда я набираю: «сделать прочитанным»)

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

4 ответы

Попробуйте добавить точку с запятой после cat testFile. Например:

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

альтернативно:

read:
    test -r testFile && cat testFile

ответ дан 25 мар ’11, в 23:03

Я столкнулся с той же проблемой. Это должно сделать это:

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

ответ дан 25 мар ’11, в 23:03

Начиная с GNU Make 3.82, вы можете добавить .ONESHELL: в начало файла, чтобы программа make запускала все строки в целевой оболочке в одной оболочке.

.ONESHELL:
SHELL := /bin/bash

foobar:
    if true
    then
        echo hello there
    fi

Смотрите пост в документации.

Добавьте строки с @ или добавить .SILENT: вариант ниже .ONESHELL: для подавления эхом линий.

Создан 17 фев.

Я тоже столкнулся с этой проблемой.

Причина в том, что я добавил несколько комментариев после «».

Создан 18 июля ’10, 03:07

Не тот ответ, который вы ищете? Просмотрите другие вопросы с метками

bash
makefile

or задайте свой вопрос.

Содержание

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

Понравилась статья? Поделить с друзьями:
  • Bin bash c line 0 syntax error near unexpected token
  • Bimatek am400 ошибка f1
  • Bilnittialibrary failed 0xc00000bb как исправить
  • Billing service unavailable on device как исправить ошибку
  • Billing error перевод