syntax error near unexpected token ‘ — bash
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
Did anyone come across the same issue ?
6 Answers 6
It could be a file encoding issue.
I have encountered file type encoding issues when working on files between different operating systems and editors — in my case particularly between Linux and Windows systems.
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:
Then try to run the new file sh ./newfile . If this works, the issue was carriage returns as hidden characters.
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
-bash: syntax error near unexpected token `newline’ for display command
I want to open a gif file using linux command.The file’s name is «Simulation of electrical activity in the heart during fibrillation (with comparison with experiment).gif».
I use the following command:
What’s wrong with it? Thank you!
1 Answer 1
gives you a syntax error near unexpected token newline is that the arrow brackets in whatever documentation you were following were not intended to be taken literally.
A indicates that the thing that follows is a filename to be used as input on stdin, and a > indicates that the thing that follows is a filename to be used for output on stdout; thus, a > at the very end of your command is a syntax error, because it expects a file name to follow, not a newline.
Not the answer you’re looking for? Browse other questions tagged linux bash syntax or ask your own question.
Related
Subscribe to RSS
To subscribe to this RSS feed, copy and paste this URL into your RSS reader.
site design / logo © 2020 Stack Exchange Inc; user contributions licensed under cc by-sa. rev 2020.9.18.37632
Syntax error near unexpected token ‘fi’
I’m trying to write a script that removes all the .jpg’s that end in an odd number. This is my code:
When I run it it outputs start and then says «syntax error near unexpected token ‘fi'»
When I had then on the line after if it said «syntax error near unexpected token ‘then'»
4 Answers 4
As well as having then on a new line, you also need a space before and after the [ , which is a special symbol in BASH.
Use Notepad ++ and use the option to Convert the file to UNIX format. That should solve this problem.
«Then» is a command in bash, thus it needs a «;» or a newline before it.
The first problem with your script is that you have to put a space after the [ .
Type type [ to see what is really happening. It should tell you that [ is an alias to test command, so [ ] in bash is not some special syntax for conditionals, it is just a command on its own. What you should prefer in bash is [[ ]] . This common pitfall is greatly explained here and here.
Another problem is that you didn’t quote «$f» which might become a problem later. This is explained here
You can use arithmetic expressions in if , so you don’t have to use [ ] or [[ ]] at all in some cases. More info here
Also there’s no need to use \n in every echo , because echo places newlines by default. If you want TWO newlines to appear, then use echo -e ‘start\n’ or echo $’start\n’ . This $» syntax is explained here
To make it completely perfect you should place — before arbitrary filenames, otherwise rm might treat it as a parameter if the file name starts with dashes. This is explained here.
Как исправить ошибку bash: syntax error near unexpected token `(‘?
bash: 4.4.12(1)-release
которая должна вывести числа Фибоначчи.
P.S.: Вообще не представляю, как это может работать, а понять ошибку в данном случае нельзя. Команда не моя.
Есть еще одна команда
которая печатает дату. И здесь всё работает нормально, а вот с Фибоначчи ошибочку получаю.
1 ответ 1
Первую команду разбирать нет желания, разберу вторую, и если хотите, по тому же принципу разбирайте первую, благо идея очень незатейливая.
Подставляем первый $ <#?>, предполагается что там будет 1, потому, что это длина кода возврата предыдущей команды. Обычно это код 0 (если не произошло обшики), соответственно его длина 1:
по маске /. /. /. 1. , после поиска по диску, найдется команда /usr/bin/sha1sum , по крайней мере на это рассчитывает скрипт:
/usr/bin/sha1sum примерно соответсвует echo «]» | /usr/bin/sha1sum . Подставляем результат:
команда : «de603c91038f329cce1cca8a30ea161b2271e2f6 -» не делает ничего полезного, но соответствующая строчка осядет в $_ , а код ошибки $? станет равным 0
Поэтому вместо последующих $ <#?>подставятся единицы, правда в моей (более ранней) версии bash такая подстановка срабатывает неправильно:
Далее подставляем подстроки переменной $_ : $ <_::1>берет ее первый символ, т.е. d , а $ <_:1:1>— второй, т.е. e
syntax error near unexpected token `do’ in bash script
I have bash script which takes 3 parameters from the command line. It compares all of the files in the directory to see if they are of the type of the first 2 parameters. If they are, the script converts such files to the type of the third parameter using an FFMPEG command. I would execute the script with the following command:
That this, this script would convert all of the .avi and .mp4 files to .flv.
When I run the script, I get the error
5 Answers 5
You have some issues with your formatting and syntax. sjsam’s advice to use shellcheck is good, but the short version is that you should be using square brackets instead of round ones on the internal brackets of your if statement:
And I don’t think you need the ‘do’ before your ffmpeg line or the curly bracket at the end of the line above, so you end up with.
For me, it was due to CRLF . It should be LF for linux env.
There are a bunch of syntax errors here. Let’s start with the line:
You need a space between if and [ (or whatever comes after it). As written, the shell is treating «if[» as the name of a command, which isn’t what you want at all.
The [ . ] style of conditional doesn’t understand || (it uses -o instead), requires that all shell metacharacters (like parentheses) be escaped or quoted, might not understand == (just = is the standard), and will get very confused if any of the unquoted variable/parameter references are blank.
if conditionals end with then (either on the next line, or after a ; ) not <
You could fix it like this:
Or, since you’re using bash (instead of a more basic shell), you can use the [[ . ]] conditional style, which has much cleaner syntax:
Next, remove the do before ffmpeg . do is part of the syntax for for and while loops; you already have one above (where it belongs), and this one just doesn’t make sense. This is what’s causing the error you see.
Next, the way you’re replacing the file’s extension won’t work right. The variable reference «$
Finally, you need a fi (after the ffmpeg line) to end the conditional. Every if needs a then and a fi .
And just as a stylistic thing, you don’t need ; at the end of a line in shell; it’s only needed when you’re putting multiple commands (or things like do and then ) on the same line. Anyway, here’s my quick rewrite: