Syntax error near unexpected token newline что значит
Bash Syntax Error Near Unexpected Token: How to Fix It
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.
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:
It’s time for the first scenario.
Syntax Error Near Unexpected Token ‘(‘
Let’s say I have the following file on my Linux system:
And I want to rename it to report_july.csv.
I can use the following command, right?
When I run it I get the following error:
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:
No errors this time:
Lesson 1: Remember to escape Bash special characters when you use them as normal characters (literals) in a filename or string in general.
Syntax Error Near Unexpected Token Then (Example 1)
And here is the second scenario.
When I run the following script:
I get back the error below:
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:
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:
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:
When you run this one-liner here’s what you get:
The syntax of a for loop in Bash is:
And using a single line:
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.
Let’s confirm the one-liner runs well after removing then:
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.
This script might seem ok, but when I run it I get the following…
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:
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:
And this is what I get when I run it:
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.
Add a command separator immediately after the closing square bracket. We will use the semicolon ( ; ) as command separator.
Our script becomes:
And if I run it I get the correct output:
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
line 7: syntax error near unexpected token `newline’ #8
Comments
hideoshiraishi commented Jan 13, 2019 •
I am trying to install RStudio to my Galaxy tab s4 (ARM 64bit) via Linux on dex but failed.
My system environment is:
DISTRIB_ID=Ubuntu
DISTRIB_RELEASE=16.04
DISTRIB_CODENAME=xenial
DISTRIB_DESCRIPTION=»Ubuntu 16.04.5 LTS»
R.version
platform aarch64-unknown-linux-gnu
arch aarch64
os linux-gnu
version R version 3.2.3
(it cannot be updated to 3.4)
ARM-RStudio.sh is placed at home directory and ran following codes in the terminal:
However, it returns the error with the following messages:
ARM-RStudio.sh: line 7: syntax error near unexpected token newline
ARM-RStudio.sh: line 7:
I tired to apply some suggestions here, here and here, however nothing solved.
I have a few years experience of using R but I am quite new to use Linux/Ubuntu.
It is highly appreciated if you have any suggestions to solve this issue.
The text was updated successfully, but these errors were encountered:
dashaub commented Jan 15, 2019
hideoshiraishi commented Jan 15, 2019
The remaining parts of the codes seem to run but RStudio is not appeared.
I worry if my environment accepts R3.4 as the official web site shows the version 3.2.
https://launchpad.net/ubuntu/xenial/arm64/r-base
(However I do not know if 3.4 is required to install RStudio)
Hope if you have any solution.
tmakowski commented Jan 15, 2019 •
@hideo-s regarding the R version, you could try building R from source. I have done so on my ARM chromebook to get the 3.5.1 version, however it was not for the RStudio purposes.
Dependencies I needed:
Downloading and unpacking:
Configuration and installation:
I hope it will be helpful in some way.
hideoshiraishi commented Jan 16, 2019
It is sorry to ask such basic issue but I am still struggling with this issue.
dashaub commented Jan 16, 2019
I’m afraid the install script isn’t working right now. I’m trying to get it working again, but I have limited access to appropriate hardware. Also when I get this working again ti would probably be with an old version of RStudio.
hideoshiraishi commented Jan 18, 2019 •
Thank you very much, I could run R 3.5.2 by specifying the program in the directory:
$ cd usr/local/bin bash R
$ bash R
On the other hand, RStudio still seems not to be installed properly.
Uncaught SyntaxError: Unexpected token — что это означает?
Самая популярная ошибка у новичков.
Когда встречается. Допустим, вы пишете цикл for на JavaScript и вспоминаете, что там нужна переменная цикла, условие и шаг цикла:
for var i = 1; i // какой-то код
>
После запуска в браузере цикл падает с ошибкой:
❌ Uncaught SyntaxError: Unexpected token ‘var’
Что значит. Unexpected token означает, что интерпретатор вашего языка встретил в коде что-то неожиданное. В нашем случае это интерпретатор JavaScript, который не ожидал увидеть в этом месте слово var, поэтому остановил работу.
Причина — скорее всего, вы пропустили что-то из синтаксиса: скобку, кавычку, точку с запятой, запятую, что-то подобное. Может быть, у вас была опечатка в служебном слове и язык его не распознал.
Что делать с ошибкой Uncaught SyntaxError: Unexpected token
Когда интерпретатор не может обработать скрипт и выдаёт ошибку, он обязательно показывает номер строки, где эта ошибка произошла (в нашем случае — в первой же строке):
Если мы нажмём на надпись VM21412:1, то браузер нам сразу покажет строку с ошибкой и подчеркнёт непонятное для себя место:
По этому фрагменту сразу видно, что браузеру не нравится слово var. Что делать теперь:
I have a written a sample script on my Mac
and this works fine by displaying Example
When I run this script on a RedHat machine, it says
syntax error near unexpected token ‘
I checked that bash is available using
6 Answers 6
It could be a file encoding issue.
I suggest checking your file’s encoding to make sure it is suitable for the target linux environment. I guess an encoding issue is less likely given you are using a MAC than if you had used a Windows text editor, however I think file encoding is still worth considering.
— EDIT (Add an actual solution as recommended by @Potatoswatter)
To demonstrate how file type encoding could be this issue, I copy/pasted your example script into Notepad in Windows (I don’t have access to a Mac), then copied it to a linux machine and ran it:
In this case, Notepad saved the file with carriage returns and linefeeds, causing the error shown above. The \r indicates a carriage return (Linux systems terminate lines with linefeeds \n only).
On the linux machine, you could test this theory by running the following to strip carriage returns from the file, if they are present:
Note: This is not an exact replication of your environment (I don’t have access to a Mac), however it seems likely to me that the issue is that an editor, somewhere, saved carriage returns into the file.
To elaborate a little, operating systems and editors can have different file encoding defaults. Typically, applications and editors will influence the filetype encoding used, for instance, I think Microsoft Notepad and Notepad++ default to Windows-1252. There may be newline differences to consider too (In Windows environments, a carriage return and linefeed is often used to terminate lines in files, whilst in Linux and OSX, only a Linefeed is usually used).
A similar question and answer that references file encoding is here: bad character showing up in bash script execution
Shell syntax error near unexpected token `done’
This shell script is supposed to add users to the system. The new users details are in a file. The shell is rejecting this script with the message:
Second attempt
Using some of the ideas from the answers, I came up with a second attempt:
This does not seem to work properly either. What’s wrong now? Seems to show arguments and runs however no users nor group have been added therefore no logs have been created
3 Answers 3
The if starting at:
is ended with the done instead of the fi that is required.
The while loop starting a couple of lines earlier:
is missing its do (another bug); if that was present, then it would also need the done at the end. Someone lost track of the indentation. (Using 2 characters per level is better than 0 or 1, but it is easier to track levels if you use 4 spaces per level.) Note that the shell hasn’t gotten around to complaining about the lack of do because the syntax for a while loop is:
Here’s a semi-decently indented version of the script. There was a missing fi at the top of the script, too.
This reports the command’s name, and the arguments expected. The 1>&2 sends the message to standard error instead of standard output. The logic here is a little bizarre even so. You check that the user is root and only then check that there are arguments. If the user is not root, you don’t check the arguments. Not entirely sensible, I submit.
We can debate the UUOC (Useless Use of Cat). There’s actually an award for it; I don’t think this qualifies. However, it would be possible to write:
Hmmm. the script is supposed to take a file name argument that specifies the users, but the cat takes a fixed file name, not the file name argument!
Similarly, arguments 2 and 3 are studiously ignored; the log files are hard-coded.
This fragment can be improved several ways:
It might be better not to exit when the user name is found; you could at least try to process the next entry. It is also odd that the report that the user exists (which terminates the processing) is recorded in Successes1.log rather than in Errors1.log ; it is treated like an error.
The group check constructs are similar and should be similarly upgraded.
The final exit in the script should be exit 1 to indicate an error exit. As already noted, this is preceded by the comment about ‘you must be root’, even though there was a check at the top for root privileges.