Syntax error near unexpected token done bash

I am getting syntax error near unexpected token done while executing my shell script: while read filename do echo "$filename" if [ -s $filename ]; then tail -10 $filename | grep `date '+%...

I am getting syntax error near unexpected token done while executing my shell script:

while read filename
do
  echo "$filename"
  if [ -s $filename ]; then
    tail -10 $filename | grep `date '+%Y-%m-%d'` >> $lastlines1
    echo "- Next Error File - " >> $lastlines1
  done
  else
  echo " no errrors"
fi

Any ideas, where am I going wrong?

mtk's user avatar

mtk

25.8k34 gold badges89 silver badges127 bronze badges

asked Jan 2, 2013 at 12:19

UNIX Learner's user avatar

1

you are closing the while before the if.

while read filename 
do 
    echo "$filename" 
    if [ -s $filename ]
    then 
        tail -10 $filename | grep date '+%Y-%m-%d' >> $lastlines1 
        echo "- Next Error File - " >> $lastlines1 
    else 
        echo " no errrors" 
    fi
done

answered Jan 2, 2013 at 12:23

BitsOfNix's user avatar

BitsOfNixBitsOfNix

4,9672 gold badges25 silver badges34 bronze badges

Let’s add some new lines and indentation:

1 while read filename; do
2     echo "$filename"
3     if [ -s $filename ]; then
4         tail -10 $filename | grep date '+%Y-%m-%d' >> $lastlines1
5         echo "- Next Error File - " >> $lastlines1
6     done
7 else
8     echo " no errrors"
9 fi

lines 6 and 9 seem to be swapped. In other words the while-do-done and if-then-else-fi clauses are overlapping. Which is wrong in shell (and most other computer languages).

answered Jan 2, 2013 at 12:29

peterph's user avatar

peterphpeterph

30k2 gold badges67 silver badges74 bronze badges

You need to use vim editor for scripting , it will shows text in RED if that syntax wrong

while read FileName 
do 
        echo "${FileName}" 

        if [ -s "${FileName}" ]; then 
            tail -10 $FileName | grep "date '+%Y-%m-%d'" >> "${lastlines1}"
            echo "- Next Error File - " >> "${lastlines1}"
        else 
            echo " no errrors" 
        fi      
done

answered Jan 2, 2013 at 12:29

Rahul Patil's user avatar

Rahul PatilRahul Patil

23.6k25 gold badges79 silver badges95 bronze badges

3

You need to complete the if statement before the do while. If you are trying to only echo no errors once if no files are found, you need to use a flag to indicate it.

errorCount=0
while read filename 
do 
    echo "$filename" 
    if [ -s $filename ]
    then 
        tail -10 $filename | grep date '+%Y-%m-%d' >> $lastlines1 
        echo "- Next Error File - " >> $lastlines1 
        errorCount=$(($errorCount + 1))
    fi
done
if [[ $errorCount -eq 0 ]]
then
    echo " no errors"
fi

answered Jan 2, 2013 at 14:37

Drake Clarris's user avatar

Sometimes this error happens because of unexpected CR characters in file, usually because the file was generated on a Windows system which uses CR line endings. You can fix this by running dos2unix or tr, for example:

tr -d '15' < yourscript.sh > newscript.sh

This removes any CR characters from the file and in new shell script file you didn’t get that error.

answered Feb 27, 2017 at 6:09

Mihit Gandhi's user avatar

Have you ever seen the message “syntax error near unexpected token” while running one of your Bash scripts?

In this guide I will show you why this error occurs and how to fix it.

Why the Bash unexpected token syntax error occurs?

As the error suggests this is a Bash syntax error, in other words it reports bad syntax somewhere in your script or command. There are many things that can go wrong in a Bash script and cause this error. Some common causes are missing spaces next to commands and lack of escaping for characters that have a special meaning for the Bash shell.

Finding the syntax error reported when you execute your script is not always easy. This process often requires you to change and retest your script multiple times.

To make your life easier I have analysed different scenarios in which this syntax error can occur. For every scenario I will show you the script or command with the error and the fix you need to apply to solve the problem.

Let’s get started!

One Approach to Fix Them All

Considering that this syntax error can occur in multiple scenarios you might not be able to find your exact error in the list below.

Don’t worry about it, what matters is for you to learn the right approach to identify what’s causing the error and knowing how to fix it.

And going through the examples below you will learn how to do that.

In some of the examples I will show you how to fix this error if it happens while executing a single command in a Bash shell.

In other examples we will look at Bash scripts that when executed fail with the “unexpected token” error.

To fix the error in a single command it’s usually enough to add or remove some incorrect characters that cause the syntax error in the command.

Knowing how to fix the error in a script can take a bit more time, and for that I will use the following 5-step process:

  1. Run the script that contains the syntax error.
  2. Take note of the line mentioned by the Bash error.
  3. Execute the line with the error in a Bash shell to find the error fast (without having to change the script and rerun it multiple times).
  4. Update your script with the correct line of code.
  5. Confirm the script works.

Makes sense?

It’s time for the first scenario.

Let’s say I have the following file on my Linux system:

-rw-r--r--  1 ec2-user ec2-user   28 Jun 28 22:29 report(july).csv

And I want to rename it to report_july.csv.

I can use the following command, right?

mv report(july).csv report_july.csv

When I run it I get the following error:

-bash: syntax error near unexpected token `('

But, why?

Because parentheses () are used in Bash to create a subshell. In other words they are special characters.

And Bash special character need to be escaped if used as normal characters in a command. The backslah is used to escape characters.

I will update the command to include the backslash before both parentheses:

mv report(july).csv report_july.csv

No errors this time:

-rw-r--r--   1 ec2-user ec2-user   28 Jun 28 22:29 report_july.csv

Lesson 1: Remember to escape Bash special characters when you use them as normal characters (literals) in a filename or string in general.

First error fixed!

Syntax Error Near Unexpected Token Then (Example 1)

And here is the second scenario.

When I run the following script:

#!/bin/bash

DAY="Monday"

if[ $DAY == "Monday" ]; then
  echo "Today is Monday"
else
  echo "Today is not Monday"
fi

I get back the error below:

(localhost)$ ./unexpected_token.sh
./unexpected_token.sh: line 5: syntax error near unexpected token `then'
./unexpected_token.sh: line 5: `if[ $DAY == "Monday" ]; then'

Can you see why?

The error is caused by the missing space between if and the open square bracket ( [ ).

And the reason is the following:

if is a shell builtin command and you might be thinking you are using if here. But in reality the shell sees if[ that is not a known command to the shell.

At that point the shell doesn’t know how to handle then given that it hasn’t found if before, and it stops the script with the error above.

The correct script is:

#!/bin/bash

DAY="Monday"

if [ $DAY == "Monday" ]; then
  echo "Today is Monday"
else
  echo "Today is not Monday"
fi

I have just added a space between if and [ so the shell can see the if command.

And the output of the script is correct:

(localhost)$ ./unexpected_token.sh
Today is Monday

Lesson 2: Spaces are important in Bash to help the shell identify every command.

Syntax Error Near Unexpected Token Then (Example 2)

While writing Bash scripts, especially at the beginning, it’s common to do errors like the one below:

(localhost)$ for i in {0..10} ; do echo $i ; then echo "Printing next number" ; done

When you run this one-liner here’s what you get:

-bash: syntax error near unexpected token `then'

Let’s find out why…

The syntax of a for loop in Bash is:

for VARIABLE in {0..10}
do
  echo command1
  echo command2
  echo commandN
done

And using a single line:

for VARIABLE in {0..10}; do echo command1; echo command2; echo commandN; done

So, as you can see the semicolon is used in Bash to separate commands when you want to write them on a single line.

The reason why the semicolons were not required in the first version of the script is that the newline is a command separator too.

Now, let’s go back to our error…

The one-liner that was failing with an error contains the then statement that as you can see is not part of the structure of a for loop.

The error is telling us:

  • There is a syntax error.
  • The token ‘then‘ is unexpected.

Let’s confirm the one-liner runs well after removing then:

(localhost)$ for i in {0..10} ; do echo $i ; echo "Printing next number" ; done
0
Printing next number
1
Printing next number
2
Printing next number
3
Printing next number
4
Printing next number
5
Printing next number
6
Printing next number
7
Printing next number
8
Printing next number
9
Printing next number
10
Printing next number

All good!

Lesson 3: When you see a syntax error verify that you are using Bash loops or conditional constructs in the right way and you are not adding any statements that shouldn’t be there.

Syntax Error Near Unexpected Token Done

I have created a simple script in which an if statement is nested inside a while loop. It’s a very common thing to do in Bash.

#!/bin/bash

COUNTER=0
  
while true 
do
  if [ $COUNTER -eq 0 ]; then
    echo "Stopping the script..."
    exit 1
  done
fi

This script might seem ok, but when I run it I get the following…

./unexpected_token.sh: line 8: syntax error near unexpected token `done'
./unexpected_token.sh: line 8: `  done'

Why?

The done and fi statements are correctly used to close the while loop and the if conditional statement. But they are used in the wrong order!

The if statement is nested into the while loop so we should be closing the if statement first, using fi. And after that we can close the while loop using done.

Let’s try the script:

(localhost)$ ./unexpected_token.sh 
Stopping the script...

All good now.

Lesson 4: Nested loops and conditional statements need to be closed in the same order in which they are opened.

Syntax Error Near Unexpected Token fi

Let’s look at another scenario in which this syntax error can occur with the fi token:

#!/bin/bash
  
for NAME in 'John' 'Mark' 'Kate'
do
    if [ "$NAME" == 'Mark' ] then
        echo 'Hello Mark!'
    fi
done

And this is what I get when I run it:

./unexpected_token.sh: line 7: syntax error near unexpected token `fi'
./unexpected_token.sh: line 7: `    fi'

In this case the Bash shell identifies the if statement and because of that it expects then after it.

As you can see then is there, so what’s the problem?

There is no command separator between the [ ] command (yes….it’s a command) and the then statement.

So, what’s the fix?

Add a command separator immediately after the closing square bracket. We will use the semicolon ( ; ) as command separator.

Our script becomes:

#!/bin/bash
  
for NAME in 'John' 'Mark' 'Kate'
do
    if [ "$NAME" == 'Mark' ]; then
        echo 'Hello Mark!'
    fi
done

And if I run it I get the correct output:

(localhost)$ ./unexpected_token.sh 
Hello Mark!

Lesson 5: Remember to specify command separators in your Bash scripts. Either the semicolon or the newline.

Conclusion

You now have what you need to understand what causes this syntax error in your scripts. You can apply the 5 lessons I have explained in this guide to find a fix.

Take the time to review the lessons at the end of each section so they become part of your Bash knowledge.

If you have any questions please feel free to write them in the comments below.

Now, let’s say you have saved your Bash script using Windows.

And when you run it in Linux you are seeing a syntax error that you can’t really explain because the script looks correct to you.

You might be having the problem explained in this article.

Enjoy your scripting!


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!

Кодирование в терминале Linux Bash стало преобладающей практикой в ​​секторе кодирования. Инженеры-программисты и студенты, изучающие язык программирования, сталкиваются с различными ошибками. Если вы неоднократно сталкивались с такими ошибками, как Синтаксическая ошибка рядом с неожиданным токеном ‘(‘ или Синтаксическая ошибка Bash рядом с неожиданным токеном, вы можете попробовать использовать методы, описанные в статье, и стать опытным программистом. Прочитайте методы, описанные в статье, в разделе порядок описан и исправьте ошибки в командных строках вашего файла.

Linux Bash — интерпретатор командной строки для системы на базе Linux, заменяющий Bourne Shell или sh. Файлы именуются в формате .sh в сценариях Linux Bash. Если в коде сценария оболочки есть проблемы с форматированием, вы можете столкнуться с синтаксической ошибкой. Если ошибка близка к символу (, оболочка подскажет вам ошибку в строке и отобразит ошибку в соответствующей строке. Поскольку Linux Bash является интерпретатором, строка с ошибкой будет возвращена вам в Терминал, и он прекратит сканирование остальных команд в сценарии. Следовательно, вам необходимо исправить ошибку в конкретной командной строке и перейти к следующей, чтобы исправить непредвиденную ошибку токена в сценарии оболочки. Причины синтаксиса ошибка рядом с неожиданным токеном в Linux Bash перечислены ниже в этом разделе, как показано ниже:

  • Кодирование с помощью escape-последовательностей. Если вы написали код в сценарии Bash, escape-последовательности или кавычки в сценарии могут вызвать ошибки. Чтобы исправить ошибку, управляющие последовательности и кавычки должны быть записаны в правильном формате.

  • Неправильный синтаксис в файле кодирования. Синтаксис в коде может привести к синтаксической ошибке, если команда написана с неправильным синтаксисом, например, с изменением порядка циклов.

  • Неправильное использование команды. Если вы неправильно используете команду, например, присваиваете неверное значение, у вас может возникнуть синтаксическая ошибка.

  • Несовместимая ОС в системах. Если оболочка для сценария кодирования несовместима между системами Unix и DOS, у вас может возникнуть непредвиденная ошибка.

  • Проблемы в сценарии оболочки bash. Проблемы, выполняемые в сценарии оболочки bash в файле, скопированном из другой системы, могут привести к непредвиденной ошибке токена.

Рассмотрим файл с именем example.sh, созданный в сценариях Linux Bash со следующими командными строками для пояснений. Файл примера допускает синтаксические ошибки и включает все возможные команды, которые можно использовать в сценарии оболочки.

str= ‘First command line of ‘(example file)’ in the script’
str= [(1,2),(3,4)]
if[ $day == “mon” ] then
 echo “mon”
else
 echo “no mon”
fi
for VARIABLE in {0..2}; then
do echo command1; echo command2; echo command3; echo command4; done
while true; do if [ $ day == “mon” ]; then echo “mon”; else echo “not mon”; done; fi

Способ 1: исправить ошибки в каждой командной строке вручную

Первый способ исправить ошибки — исправить синтаксическую ошибку вручную в каждой командной строке скрипта. В этом разделе обсуждаются шаги по устранению синтаксических ошибок рядом с неожиданным токеном в командных строках. Процесс исправления непредвиденной ошибки токена в Терминале описан ниже. Запустите файл в Терминале, введя команду ./example.sh и нажав клавишу Enter.

2. Обратите внимание на строки с непредвиденной ошибкой токена в командных строках результата ниже.

3. Исправьте ошибку в каждой строке, следуя описанным ниже методам по отдельности и сохранив файл.

4. После внесения изменений снова запустите файл и проверьте, устранена ли синтаксическая ошибка в файле.

Шаг I: Чтение содержимого файла

Первым шагом к устранению синтаксической ошибки в командной строке является чтение файла в Терминале. ЕСЛИ есть проблемы с файлом, возможно, вы не сможете просмотреть файл. Обычная практика просмотра файла заключается в запуске файла с помощью команды ./example.sh, но вы не можете изменить содержимое файла. Варианты просмотра содержимого файла и изменения командных строк для исправления синтаксической ошибки рядом с неожиданным токеном ‘(‘ обсуждаются ниже.

Вариант 1: через CAT-команду

Первый вариант — использовать команду cat для просмотра файла в сценарии оболочки. Прочтите содержимое файла с неожиданной ошибкой токена с помощью команды cat, введя команду cat –v example.sh в Терминале.

Примечание 1. Файл example.sh используется в пояснительных целях, и вам необходимо ввести имя файла с непредвиденной ошибкой токена.

Примечание 2. Команда cat –v используется для отображения всех невидимых символов, которые могут представлять собой возврат каретки или пробел без разрыва.

Вариант 2: Через команду VX

Если вы не можете использовать команду cat, вы можете попробовать использовать команду vx для просмотра и изменения команд в файле, используя шаг, указанный ниже. Введите команду sh –vx ./example.sh в Терминале, чтобы открыть файл.

Вариант 3: Через od –a Command

3. Если в командной строке есть несколько невидимых символов, вы можете использовать команду od –a для просмотра файла. Если содержимое файла не видно в файле кода, вы можете попробовать прочитать файл, используя команду od –a example.sh для изменения кода.

Шаг II. Удалите разрывы строк Windows

Если в сценарии оболочки есть разрывы строк Windows, вы можете использовать консольные команды, чтобы удалить разрывы строк и скопировать строки кода в новый файл, чтобы исправить ошибку.

Введите следующую команду в Терминале, чтобы сохранить содержимое файла в другой файл с именем correctedexample.sh, чтобы удалить разрывы строк Windows в сценарии.

tr –d ‘r’ <example.sh> correctedexample.sh

Шаг III: Установите разрешения для вновь созданного файла

Вам необходимо установить разрешение для вновь созданного файла для редактирования файла, чтобы файл можно было выполнить в оболочке. Введите команду как chmod 755 correctedexample.sh в Терминале, чтобы предоставить права доступа к файлу и запустить файл. Теперь вы можете просмотреть исправленный файл и исправить проблемы с форматированием, а также исправить синтаксическую ошибку рядом с неожиданным токеном ‘(‘ в файле.

Шаг IV: форматирование кода в файле

Второй шаг — отформатировать строки кода по отдельности и вручную изменить командные строки в файле. Варианты форматирования файла для исправления синтаксической ошибки рядом с неожиданным токеном ‘(‘ обсуждаются ниже в этом разделе.

Вариант 1: заменить одинарные кавычки двойными кавычками

Если вы используете одинарные кавычки в командной строке, вам нужно изменить команду, заменив одинарную кавычку двойными, чтобы исправить синтаксическую ошибку. В файле example.sh удалите строки кода, содержащие ‘ и ‘ или одинарные кавычки в команде, и замените одинарные кавычки двойными кавычками или » и ». Здесь, в файле примера, вам нужно изменить код как str= «Первая командная строка «(файл примера)» в скрипте»

Примечание. Двойные кавычки необходимы для команд типа параметра, таких как str= “[(1,2),(3,4)]».

Вариант 2: добавить $ к строковым строкам

Если вы добавили строковые значения в скрипт, вам нужно добавить $ к строковым значениям, чтобы исправить синтаксическую ошибку в скрипте. Добавьте $ для командных строк со строковыми значениями, чтобы исправить непредвиденную ошибку. Здесь, в файле примера, измените командную строку как;

str= $ ‘First command line of ‘(example file)’ in the script’

Примечание. Если вы используете $ в строковом значении, вы можете обойти escape-последовательность обратной косой черты, поскольку командные строки декодируются по стандарту ANSI C. Другими словами, используя $ для строкового значения, вы можете избежать использования двойных кавычек вместо одинарных в командных строках.

Вариант 3: преобразовать вкладки в пробелы

Пробелы, которые вы оставили между двумя операторами в команде, должны быть пробелами, а не табуляцией, чтобы исправить синтаксическую ошибку в сценарии. Если вы получаете ошибку на Cygwin, вы можете попробовать преобразовать вкладки в кодах в пробелы, чтобы исправить ошибку. Командная строка представлена ​​ниже как;

do echo command1;       echo command2;             echo command3;             echo command4;             done

Приведенную выше команду следует переписать, как показано ниже, чтобы исправить ошибку.

do echo command1; echo command2; echo command3; echo command4; done

Вариант 4. Используйте escape-символы

Если вы используете символ bash, важно использовать escape-символ вместе с символом bash, чтобы исправить синтаксическую ошибку. Круглые скобки или () являются специальными символами bash в файле, поэтому вам нужно будет использовать escape-символ или обратную косую черту в командной строке, чтобы экранировать обычные символы для выполнения команды. Команда str= ‘Первая командная строка ‘(пример файла)’ в команде script’ не выдаст ошибку в Терминале, поскольку используется escape-символ.

Вариант 5. Используйте пробелы между символами

Сценарий оболочки распознает команды и операторы в сценарии по значениям по умолчанию. Вам необходимо обеспечить правильное использование пробелов между символами, чтобы оболочка могла идентифицировать команду, указанную в сценарии. Пробел — это символ, который используется для различения двух символов в командной строке. В коде нет пробела между if и [, which gives the unexpected token error as the if[ command is not identified by the shell. If the code is changed to if [ $ day == “mon” ]; тогда ошибка может быть решена с помощью команды бюллетеня оболочки, если она идентифицируется оболочкой.

Вариант 6. Используйте разделитель команд для операторов

Различные команды в сценарии оболочки должны быть разделены на операторы, чтобы Терминал мог идентифицировать отдельные команды. Вам нужно использовать разделитель команд, чтобы исправить синтаксическую ошибку в Linux Bash. Операторы в команде должны быть разделены разделителем команд, таким как точка с запятой или ; или новую строку, нажав клавишу Enter. Например, команда в коде if [ $ day == “mon” ] тогда нужно изменить, как если бы [ $ day == “mon” ]; затем исправить ошибку. Поскольку точка с запятой используется в качестве разделителя команд между символами [ and then, you can fix this error.

Option 7: Remove Additional Statements

Sometimes, you may have added additional statements or may have mixed up the codes in case of multiple nested loops. You need to remove the additional statements on the command lines to fix the Syntax error near unexpected token ‘(’ in the Linux Bash. The bash loops for…done or and the constructional constructs if… fi needs to be in the correct syntax. The example file has the wrong syntax in the for loop has the term then which is used in the if statement. Modifying the code as the following code will fix the unexpected token error. The statement then is an additional statement in the code and removing the term will fix the error.

for VARIABLE in {0..2}; do echo command1; echo command2; echo command3; echo command4; done 

Option 8: Ensure Order of Closing of Statements is Correct

If you are using many nested or conditional construct statements in the shell script, you have to ensure that the loops are closed in the order they are opened. You can use a new line separator to avoid conflicts with the loops. The order of closing the nested loops and conditional statements should be correct and must not be altered. The loops in the code while true; do if [ $ day == “mon” ]; затем эхо «мон»; иначе эхо «не пн»; Выполнено; fi нужно закрывать в правильном порядке. Изменение кода, как показано ниже, может исправить непредвиденную ошибку токена, поскольку порядок закрытия операторов исправлен.

while true; do if [ $ day == “mon” ]; then echo “mon”; else echo “not mon”; fi; done

Способ 2: переписать код

Если вы скопировали код и вставили его в новый файл в Терминале, вы можете попробовать переписать код вручную, чтобы исправить ошибку. Ошибки в коде можно исправить, если вы написали код без каких-либо ошибок формата в сценарии оболочки. Это связано с тем, что скрытые символы и проблемы с форматированием в текстовом редакторе, таком как Microsoft Word, которые вы могли использовать для копирования и вставки кода, могли привести к ошибке.

Способ 3: используйте команду Dos2unix.exe

Если вы используете операционную систему Unix, вы можете писать коды с символом перевода строки как n, чтобы перейти к следующей строке в файле. Однако, если вы используете ОС Windows, вам нужно перейти к следующей строке в коде, используя возврат каретки и перевод строки или rn в файле. Если вы выполняете код, написанный в ОС Windows, в Cygwin, вы можете получить синтаксическую ошибку рядом с неожиданным токеном ‘(‘.

Чтобы исправить ошибку, вам нужно очистить символы возврата каретки, используя инструмент командной строки DOS в Unix в качестве конвертера формата текстового файла. Введите следующую команду как dos2unix.exe example.sh в терминале, и вы сможете преобразовать файл в формат Unix.

***

В статье обсуждались основные методы исправления синтаксической ошибки Bash рядом с неожиданным токеном ‘(‘ в сценарии. Если вы используете Linux Bash, вы можете использовать методы, описанные в этом разделе, для исправления синтаксической ошибки Bash рядом с неожиданным токеном. Если вы Если вы прочитали всю статью и нашли ее содержание полезным, сообщите нам о своих предложениях и вопросах в разделе комментариев.

Run cat -v file.sh.

You most likely have a carriage return or no-break space in your file. cat -v will show them as ^M and M-BM- or M- respectively. It will similarly show any other strange characters you might have gotten into your file.

Remove the Windows line breaks with

tr -d r < file.sh > fixedfile.sh

I was getting the same error on Cygwin; I did the following (one of them fixed it):

  1. Converted TABS to SPACES
  2. ran dos2unix on the .(ba)sh file

BASH Syntax error near unexpected token done

What is the error youre getting?

$ bash file.sh
test.sh: line 8: syntax error: unexpected end of file

If you get that error, you may have bad line endings. Unix uses <LF> at the end of the file while Windows uses <CR><LF>. That <CR> character gets interpreted as a character.

You can use od -a test.sh to see the invisible characters in the file.

$ od -a test.sh
0000000    #   !   /   b   i   n   /   b   a   s   h  cr  nl   #  sp  cr
0000020   nl   w   h   i   l   e  sp   :  cr  nl   d   o  cr  nl  sp  sp
0000040   sp  sp   e   c   h   o  sp      P   r   e   s   s  sp   [   C
0000060    T   R   L   +   C   ]  sp   t   o  sp   s   t   o   p     cr
0000100   nl  sp  sp  sp  sp   s   l   e   e   p  sp   1  cr  nl   d   o
0000120    n   e  cr  nl                                                
0000124

The sp stands for space, the ht stands for tab, the cr stands for <CR> and the nl stands for <LF>. Note that all of the lines end with cr followed by a nl character.

You can also use cat -v test.sh if your cat command takes the -v parameter.

If you have dos2unix on your box, you can use that command to fix your file:

$ dos2unix test.sh

Related posts on BASH Syntax error  :

  • shell – unary operator expected error in Bash if condition
  • linux – syntax error near unexpected token `else
  • bash – Shell Script: correct way to declare an empty array
  • bash – Basic if else statement in Makefile
  • linux – Comprehensive list of rsync error codes
  • bash – Integer expression expected error in shell script
  • bash – In the shell, what does 2>&1 mean?
  • bash – Syntax error near unexpected token fi

10 More Discussions You Might Find Interesting

1. Ubuntu

Syntax error near unexpected token `(‘

detect_mouse_mvt.sh
/home/andy/bin/detect_mouse_mvt.sh: line 4: syntax error near unexpected token `(‘
/home/andy/bin/detect_mouse_mvt.sh: line 4: `fh = file(‘/dev/input/mice’)’
#!/bin/bash
#
#
fh = file(‘/dev/input/mice’)
while True:
fh.read(3)
print ‘Mouse… (15 Replies)

Discussion started by: drew77

2. UNIX for Beginners Questions & Answers

Syntax error near unexpected token

Dears,

While executing the below script im getting the error at line 30. Please let me know what changes to be done to fix this.

test.sh: line 30: syntax error near unexpected token `done’
test.sh: line 30: ` done ‘

#!/bin/sh
# Rev. PA1
# author: eillops
# date: 26-04-2018
#
#… (1 Reply)

Discussion started by: Kamesh G

3. How to Post in the The UNIX and Linux Forums

Syntax error near unexpected token `(‘

I have 2 files like a.txt and b.txt and the content is as below

cat a.txt

810750125 117780 /BSCSQAT4A/bscsqat4a/lib/jar/wclt_common.jar
1803152428 13300 /BSCSQAT4A/bscsqat4a/lib/jar/WFMSSupportTool.jar
2663502779 67049 /BSCSQAT4A/bscsqat4a/lib/jar/wma.jar
687942896 665272… (1 Reply)

Discussion started by: ranabhavish

4. Shell Programming and Scripting

Syntax error near unexpected token

Hi all,

I have a simple script that doesn’t work somehow. I can’t seem to be spotting the cause of the malfunction.

count=$((1))
for item in `cat test1.txt`
printf %s `sed -n $((count))p test2.txt` > test3.txt
count=$((count+1))
do
something
done
I get ;

./why.sh: line 3:… (14 Replies)

Discussion started by: y33t

5. Shell Programming and Scripting

Syntax error near unexpected token ‘(‘

I tried to execute the code but I got this error
./Array.c: line 9: syntax error near unexpected token ‘(‘
./Array.c: line 9: ‘ nvals = get_data(a,MAXARRAY);’

and
#include<stdio.h>
#define MAXARRAY 1000
main()
{
int a,
nvals;
nvals =… (7 Replies)

Discussion started by: sgradywhite

6. Shell Programming and Scripting

Syntax error near unexpected token `else’

Hi,

I am trying to read the session log through script. But it keeps showing me some error near. I have tried everything. Even tried converting the script using sed command to remove the hidden characters(r).But nothing seems to be working.Below is the script :

#!/bin/bash
cd… (6 Replies)

Discussion started by: Aryan12345

7. Shell Programming and Scripting

Syntax error near unexpected token `(‘

What do I do here?

#!/bin/bash
payload=-1 AND 1=IF(21,BENCHMARK(5000000,MD5(CHAR(115,113,108,109,97,112))),0)#
hash=`echo -n $payload md5sum tr -d ‘n’ sed ‘ss-sg’ md5sum tr -d ‘n’ sed ‘ss-sg’`
curl —data cs2=chronopay&cs1=$payload&cs3=$hash&transaction_type=rebill… (2 Replies)

Discussion started by: iiiiiiiiiii

8. Shell Programming and Scripting

syntax error near unexpected token `=’

Hi all,
This is a script which converts hex to bin. However am finding an error while executing

syntax error near unexpected token `=’

`($hexfile, $binfile) = @ARGV;’

I am running using ./fil.pl <hexfile> <binfile>

###################################################
#
# this script… (3 Replies)

Discussion started by: jaango123

9. UNIX for Advanced & Expert Users

syntax error near unexpected token ‘{

Hi,

I am running the following script through cygwin and getting below mentioned error.
*******************************************

#!/bin/sh

# constants
WORK_DIR=»deploy»
INFOFILE=»deploy.info»
INTROFILE=»Intro.sh»
CMGMT_PKG=»com.kintana.cmgmt.deploy»
DEPLOY_PREFIX=»mitg»
(2 Replies)

Discussion started by: MandyR

10. Shell Programming and Scripting

sh syntax error unexpected token done

I’m getting the following error:

line 21: syntax error near unexpected token `done`
line 21: `done`

and I haven’t been able to figure out why.

Here is my code

#!/bin/sh
if ; then
echo ‘Usage: rename getexp/replStr ‘
exit 0
fi
arg = $1
shift
while ; do (5 Replies)

Discussion started by: NullPointer

Bash (syntax error near unexpected token `done’)

Модераторы: /dev/random, Модераторы разделов

Аватара пользователя

kapa

Сообщения: 143

Bash

bash 3.00.16
Пишу:

Код: Выделить всё

while :
do check_kassir() {
if mount_smbfs -I 192.168.1.25 -N -W OFIS //ROOT@STOUN/123 /123 | grep "Operatio
n timed out" > /dev/null;
then sleep 300;
elif
/root/refresh_mac_ip;
exit }
check_kassir
sleep 3;
done

Выдаёт:

Код: Выделить всё

./mount_kassir: line 10: syntax error near unexpected token `done'
./mount_kassir: line 10: `done'

Я не силён в программировании — никак не могу понять в чём ошибка.
Не подскажете?

Аватара пользователя

madskull

Сообщения: 1019
Статус: Экс-металлюга
Контактная информация:

Re: Bash

Сообщение

madskull » 27.02.2006 18:36

вместо elif подразумевалось fi , видимо.
Вообще-то странно все это. Почему бы не вынести объявление функции за цикл?

ArchLinux / IceWM

Аватара пользователя

kapa

Сообщения: 143

Re: Bash

Сообщение

kapa » 27.02.2006 18:43

madskull писал(а): ↑

27.02.2006 18:36

вместо elif подразумевалось fi , видимо.
Вообще-то странно все это. Почему бы не вынести объявление функции за цикл?

на fi он ругается так же как и на done
не вынести за цикл, потому что комп кассира может выключаться и включаться, ровно как и ребутиться маршрутер, на котором это должно крутиться, а скрипт, который обновляет пары ip-mac — как раз тащит их с компа кассира. (по-другому не придумал как реализовать)

Аватара пользователя

JaGoTerr

Сообщения: 380

Re: Bash

Сообщение

JaGoTerr » 27.02.2006 18:47

(madskull @ Feb 27 2006, в 18:36) писал(а):вместо elif подразумевалось fi , видимо.

Скорее всё же else.

А elif должен быть с условием, а не сам по себе.

(kapa @ Feb 27 2006, в 18:43) писал(а):не вынести за цикл, потому что…

Вынести нужно не вызов, а определение! Ибо оное в цикле не может быть оправдано никакой задачей.
Типа того:

function check () {
#всё что угодно
}

while true; do
check
done

Аватара пользователя

kapa

Сообщения: 143

Re: Bash

Сообщение

kapa » 27.02.2006 19:17

спасибо, сделал так:

Код: Выделить всё

if mount_smbfs -I 192.168.1.25 -N -W OFIS //ROOT@STOUN/123 /123 | grep "Operatio
n timed out";# > /dev/null;
then echo "no connection";
sleep 30;
else
/root/refresh_mac_ip;
fi;
}
while true; do
check_kassir
sleep 3;
done

монтирует, но на fi ругается постоянно также

Аватара пользователя

ddc

Бывший модератор
Сообщения: 3535
Статус: OpenBSD-compatible
ОС: OpenBSD -current

Re: Bash

Сообщение

ddc » 28.02.2006 01:50

kapa
А если убрать ‘;’?

Аватара пользователя

Shura

Сообщения: 1537
Статус: Оказывается и без KDE есть жизнь
ОС: FreeBSD 8.0-RC2

Re: Bash

Сообщение

Shura » 28.02.2006 12:38

у меня было похожее. Возьми условие в скобки.

Rock’n’roll мертв © БГ

Nab

Сообщения: 257
Контактная информация:

Re: Bash

Сообщение

Nab » 28.02.2006 16:47

блин, я наверно устарел :)
ну а если условие-то в квадратные скобки включить?
по правилам….

Чтобы правильно задать вопрос, нужно знать больше половины ответа…
FREESCO in Ukraine

Аватара пользователя

madskull

Сообщения: 1019
Статус: Экс-металлюга
Контактная информация:

Re: Bash

Сообщение

madskull » 28.02.2006 17:00

Никаких скобок не надо.
Но я сомневаюсь, что тот код, который привел kapa вообще работает.
Поскольку нет объявления функции. А раз нет ее, то я склонен подозревать, что мы еще что-то не видим.

ArchLinux / IceWM

Аватара пользователя

Sparky

Сообщения: 604
Статус: core dumped
ОС: Plan 9

Re: Bash

Сообщение

Sparky » 28.02.2006 17:48

madskull писал(а): ↑

28.02.2006 17:00

Никаких скобок не надо.
Но я сомневаюсь, что тот код, который привел kapa вообще работает.
Поскольку нет объявления функции. А раз нет ее, то я склонен подозревать, что мы еще что-то не видим.

Я так понимаю он вот так вот объявляет какраз:

Код: Выделить всё

check_kassir() {
if mount_smbfs -I 192.168.1.25 -N -W OFIS //ROOT@STOUN/123 /123 | grep "Operatio
n timed out" > /dev/null;
then sleep 300;
elif
/root/refresh_mac_ip;
exit }

Тоесть должно быть что то вроде этого:

Код: Выделить всё

#!/bin/bash
function check_kassir() {
if mount_smbfs -I 192.168.1.25 -N -W OFIS //ROOT@STOUN/123 /123 | grep "Operatio
n timed out" > /dev/null; // что вернет эта строка if?
then  sleep 300;
elif
/root/refresh_mac_ip;
exit
}

while ....

Блог
———————

GCS/M/MU/P/IT/E d- s: a- C++(+++) UBL++ P->— L+++$ E- W+++$ N* o? K? w>—
O M-@ V- PS@ PE+ Y+ PGP+ t 5 X R* tv—>- b++ DI? D>+ G e+(++) h— r+ y++

Аватара пользователя

kapa

Сообщения: 143

Re: Bash

Сообщение

kapa » 28.02.2006 18:46

ещё раз всем спасибо, к сожалению, сегодня не мог попробовать что-то изменить — постараюсь завтра и обязательно отпишусь

2 madskull:

прошу прощения, в своём ответе — верх случайно обрезал…
сделал всё как советовал JaGoTerr

Понравилась статья? Поделить с друзьями:
  • Syntax error missing parentheses in call to print ошибка
  • Syntax error missing operator in query expression
  • Syntax error last token seen t garbled time
  • Syntax error json parse error
  • Syntax error invalid syntax перевод