Ubuntu синтаксическая ошибка рядом с неожиданным маркером

Summary

Use:

if [ "$a" = 1 ]; then echo yes; fi

Full answer

The error reported by bash: -bash: syntax error near unexpected token `}’ is an attempt to guide the code writer to the error, but bash can easily get it wrong and signal an error where it isn’t.

Actually, there are several errors in the code. But let’s reproduce the error that bash reports in a simpler code line:

$ if true then { true; } fi;
bash: syntax error near unexpected token `}'

If the line changes a little, the error is reported at about the same place but a little different:

$ if true then true; fi;
bash: syntax error near unexpected token `fi'

And, this also report an error:

$ if true; then; true; fi;
bash: syntax error near unexpected token `;'

All of that happens because the syntax required (copied from the manual) is:

if list; then list; fi;

where list is one or several simple commands (or pipes, or compound commands) that end in a newline or a semicolon. Note that, in general, a newline could be replaced with a semicolon and viceversa.

This is valid (no syntax error reported)

if   true;   then   true;   fi

This is also valid:

if     true
then   true
fi

or:

if echo start; true; then echo decision; true; echo next; fi;

Or other variations of newlines and/or semicolons.

Of course, the last semicolon is not required but not forbidden.

Additionally, the [ and ] require (usually) spaces to be differentiated by bash as words (tokens) and therefore be understood as a test

if [ $a == 1 ]; then { echo 'yes'; } fi;       # still subtly incorrect.

But, also, a variable expansion should be quoted ("$a"), the == is valid in bash, but it may be invalid in some other shells, so we rather should use a = inside single [ ], the 'yes' technically doesn’t need to be quoted (even if it is no harmful), and the braces { } are not needed for a single simple command, all that makes this a better version:

if [ "$a" = 1 ]; then echo yes; fi

Or, if you choose to use bash/ksh/zsh [[ ]]:

if [[ $a == 1 ]]; then echo yes; fi

And, lastly, the test with either = or == is a string comparison, not numerical, so +1 would not be equal to 1 even if they are in value. To test numerically, you could use -eq.

результатом wc -w будет числовое значение, оно не может быть сравнено указанным вами способом = с строковым значением null. В вашем случае нужно использовать, конструкцию -eq 0. К тому-же вы в условии ставите 2-е константы, тоесть выражение

"pidof python2 run.py | wc -w" так и останется строкой

pidof python2 run.py | wc -w.

Для того, чтобы это выражение выдало результат, используйте

$(pidof python2 run.py | wc -w).

В общем итоге ваше условие, как я его понял, должно выглядеть следующим образом:

if [ "$(pidof python2 run.py | wc -w)" -eq 0 ]; then

Более того, мне кажется целесообразние, в вашем случае, использовать условие:

if [ -z "$(pidof python2 run.py)" ]; then

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

Claudio Sabato - Codefather - Software Engineer and Programming Coach

I’m a Software Engineer and Programming Coach. I want to help you in your journey to become a Super Developer!


Oftentimes when we are using Bash scripting or the git add command, we can run into this error “syntax error near unexpected token `newline’”. What exactly does this code mean? Why does this code occur and what measures can we take to avoid this error? In the following article, we will answer all those queries for you.

The main reason that this error is invoked is that we do not follow the correct syntax in “.sh” file or with the use of git add. This section enlists all the reasons for the error “syntax error near unexpected token” and their respective solutions.

Reason 1: Bash Scripting 

Make sure you are using the correct notations to initialize strings inside the bash file. To view the code of your bash script, you can use the following command:

$ cat <bash-script>

Where the <bash-script> denotes a “.sh” file.

In our case, we have used the following command to get its content:

$ cat samplefile.sh

As you can see that we are trying to use the “< >” (angle-brackets) while initializing a variable. We have executed the script to see how it behaves in the snippets below:


Solution

Every language has its notations and keywords that must be followed to avoid any execution/compilation error. The same goes for the “< >” (angle-brackets) signs in bash scripting. The “< >” (starting and ending angle brackets) together are used as placeholders in bash scripting and should not be used while writing strings.

Use of “< >” in strings

If you want to make use of “< >” in the strings, you can use them alongside quotation marks. A sample is shown below:

Let’s demonstrate how you can use these “< >” in bash scripting. Check out the correct syntax in the snippet below:

Now that we have placed quotations around these “< >” (angle brackets) as can be seen in the above image, we can execute the bash script without the error:

Reason 2: “git add” command

A similar error occurs while using the git add command. If you use the “< >” (angle-brackets) with the git add command this error will be invoked as shown below:

Solution: Remove Brackets

To fix this issue we simply need to remove the “< >” (angle-brackets) from the command and the error will be fixed as shown in the following snippet:

Conclusion

The “syntax error near unexpected token ‘newline’” error is invoked when we mess up the bash scripting syntax does not use the proper syntax to execute the git add command. The main problem with the syntax involves the “< >” bracket as it should not be used in both cases. You can wrap quotations around the “< >” (angle-brackets) to avoid this error in bash scripts as well as in git add. The way to fix it is to wrap the brackets with quotations so that it is read as a string. We have explained all these reasons and shown the practical implementation of solutions.

  • Печать

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

Тема: синтаксическая ошибка рядом с неожиданным маркером «newline»  (Прочитано 22429 раз)

0 Пользователей и 1 Гость просматривают эту тему.

Оффлайн
Ivan_ska

Здрям! По задумке должна выполняться команда в терминале, но что-то идет не так на строке 3.

#!/bin/bash
TO_RUN=$(whiptail --title "Network connection status" --menu "Choose item" 15 100 5 "1" "отображение списка портов, ожидающих подключения" "2" "отображение списка исходящих соединений" "3" "отображение списка входящих соединений" "4" "отображение статистики по выбранному сетевому протоколу" "5" "отображение таблицы маршрутизации" 3>&1 1>&2 2>&3)
case  $TO_RUN in
"1" ) terminal -- netstat -tulpn;;
"2" ) terminal -- netstat -nputw;;
"3" ) terminal -- netstat -l;;
"4" ) terminal -- netstat -e -s;;
"5" ) terminal -- netstat -r;;
esac

« Последнее редактирование: 19 Января 2023, 16:11:40 от ALiEN175 »


Оффлайн
ALiEN175

Проверьте формат файла скрипта: кодировка UTF8; перенос строк LF (не CRLF!)


Пользователь добавил сообщение 19 Января 2023, 16:20:18:


проверить можно

cat -A файл_скриптаВ конце строк перед $ не должно быть ^M

« Последнее редактирование: 19 Января 2023, 16:20:18 от ALiEN175 »

ASUS P5K-C :: Intel Xeon E5450 @ 3.00GHz :: 8 GB DDR2 :: Radeon R7 260X :: XFCE
ACER 5750G :: Intel Core i5-2450M @ 2.50GHz :: 6 GB DDR3 :: GeForce GT 630M :: XFCE


Оффлайн
Ivan_ska

Есть такое, а убрать как? В Notepadqq и текстовом редакторе не видно.

p.s. Все спасибо за ответы, тут визуальная проверка — просто жесть )

p.p.s
Исправил, спасибо!

Опять сломалось. Не работают пункты со второго по пятый, подозреваю, что дело в отступах, но при указании » 2″ вообще перестает работать.

« Последнее редактирование: 19 Января 2023, 16:42:21 от Ivan_ska »


Оффлайн
ALiEN175

Выкладывайте, пожалуйста, текстом.

ASUS P5K-C :: Intel Xeon E5450 @ 3.00GHz :: 8 GB DDR2 :: Radeon R7 260X :: XFCE
ACER 5750G :: Intel Core i5-2450M @ 2.50GHz :: 6 GB DDR3 :: GeForce GT 630M :: XFCE


  • Печать

Страницы: [1]   Вверх

Понравилась статья? Поделить с друзьями:
  • Ubuntu проверить диск на ошибки при загрузке
  • Unable to find mesh ошибка mount and blade
  • Ubuntu проверить диск на ошибки и битые сектора
  • Unable to find language file watch dogs legion ошибка
  • Ubuntu при загрузке ошибка could