Неперехваченная синтаксическая ошибка неожиданный токен

I am running an AJAX call in my MooTools script, this works fine in Firefox but in Chrome I am getting a Uncaught SyntaxError: Unexpected token : error, I cannot determine why. Commenting out code to

I am running an AJAX call in my MooTools script, this works fine in Firefox but in Chrome I am getting a Uncaught SyntaxError: Unexpected token : error, I cannot determine why. Commenting out code to determine where the bad code is yields nothing, I am thinking it may be a problem with the JSON being returned. Checking in the console I see the JSON returned is this:

{"votes":47,"totalvotes":90}

I don’t see any problems with it, why would this error occur?

vote.each(function(e){
  e.set('send', {
    onRequest : function(){
      spinner.show();
    },
    onComplete : function(){
      spinner.hide();
    },
    onSuccess : function(resp){
      var j = JSON.decode(resp);
      if (!j) return false;
      var restaurant = e.getParent('.restaurant');
      restaurant.getElements('.votes')[0].set('html', j.votes + " vote(s)");
      $$('#restaurants .restaurant').pop().set('html', "Total Votes: " + j.totalvotes);
      buildRestaurantGraphs();
    }
  });

  e.addEvent('submit', function(e){
    e.stop();
    this.send();
  });
});

asked Jun 29, 2010 at 18:37

trobrock's user avatar

trobrocktrobrock

46k11 gold badges38 silver badges45 bronze badges

6

Seeing red errors

Uncaught SyntaxError: Unexpected token <

in your Chrome developer’s console tab is an indication of HTML in the response body.

What you’re actually seeing is your browser’s reaction to the unexpected top line <!DOCTYPE html> from the server.

miken32's user avatar

miken32

41.1k16 gold badges106 silver badges148 bronze badges

answered Oct 28, 2014 at 17:56

andy magoon's user avatar

andy magoonandy magoon

2,8512 gold badges19 silver badges14 bronze badges

9

Just an FYI for people who might have the same problem — I just had to make my server send back the JSON as application/json and the default jQuery handler worked fine.

answered Aug 28, 2010 at 20:19

Edward Abrams's user avatar

Edward AbramsEdward Abrams

8851 gold badge6 silver badges3 bronze badges

5

This has just happened to me, and the reason was none of the reasons above. I was using the jQuery command getJSON and adding callback=? to use JSONP (as I needed to go cross-domain), and returning the JSON code {"foo":"bar"} and getting the error.

This is because I should have included the callback data, something like jQuery17209314005577471107_1335958194322({"foo":"bar"})

Here is the PHP code I used to achieve this, which degrades if JSON (without a callback) is used:

$ret['foo'] = "bar";
finish();

function finish() {
    header("content-type:application/json");
    if ($_GET['callback']) {
        print $_GET['callback']."(";
    }
    print json_encode($GLOBALS['ret']);
    if ($_GET['callback']) {
        print ")";
    }
    exit; 
}

Hopefully that will help someone in the future.

answered May 2, 2012 at 11:35

Grim...'s user avatar

Grim…Grim…

16.3k7 gold badges42 silver badges60 bronze badges

3

I have just solved the problem. There was something causing problems with a standard Request call, so this is the code I used instead:

vote.each(function(element){                
  element.addEvent('submit', function(e){
    e.stop();
    new Request.JSON({
      url : e.target.action, 
      onRequest : function(){
        spinner.show();
      },
      onComplete : function(){
        spinner.hide();
      },
      onSuccess : function(resp){
        var j = resp;
        if (!j) return false;
        var restaurant = element.getParent('.restaurant');
        restaurant.getElements('.votes')[0].set('html', j.votes + " vote(s)");
        $$('#restaurants .restaurant').pop().set('html', "Total Votes: " + j.totalvotes);
        buildRestaurantGraphs();
      }
    }).send(this);
  });
});

If anyone knows why the standard Request object was giving me problems I would love to know.

answered Jun 30, 2010 at 20:27

trobrock's user avatar

trobrocktrobrock

46k11 gold badges38 silver badges45 bronze badges

6

I thought I’d add my issue and resolution to the list.

I was getting: Uncaught SyntaxError: Unexpected token < and the error was pointing to this line in my ajax success statement:

var total = $.parseJSON(response);

I later found that in addition to the json results, there was HTML being sent with the response because I had an error in my PHP. When you get an error in PHP you can set it to warn you with huge orange tables and those tables were what was throwing off the JSON.

I found that out by just doing a console.log(response) in order to see what was actually being sent. If it’s an issue with the JSON data, just try to see if you can do a console.log or some other statement that will allow you to see what is sent and what is received.

answered Dec 19, 2013 at 2:50

Keven's user avatar

KevenKeven

3,92114 gold badges57 silver badges77 bronze badges

2

When you request your JSON file, server returns JavaScript Content-Type header (text/javascript) instead of JSON (application/json).

According to MooTools docs:

Responses with javascript content-type will be evaluated automatically.

In result MooTools tries to evaluate your JSON as JavaScript, and when you try to evaluate such JSON:

{"votes":47,"totalvotes":90}

as JavaScript, parser treats { and } as a block scope instead of object notation. It is the same as evaluating following «code»:

"votes":47,"totalvotes":90

As you can see, : is totally unexpected there.

The solution is to set correct Content-Type header for the JSON file. If you save it with .json extension, your server should do it by itself.

answered Dec 29, 2015 at 14:38

Michał Perłakowski's user avatar

It sounds like your response is being evaluated somehow. This gives the same error in Chrome:

var resp = '{"votes":47,"totalvotes":90}';
eval(resp);

This is due to the braces ‘{…}’ being interpreted by javascript as a code block and not an object literal as one might expect.

I would look at the JSON.decode() function and see if there is an eval in there.

Similar issue here:
Eval() = Unexpected token : error

Community's user avatar

answered Aug 13, 2015 at 19:39

Zectbumo's user avatar

ZectbumoZectbumo

3,6501 gold badge30 silver badges24 bronze badges

This happened to me today as well. I was using EF and returning an Entity in response to an AJAX call. The virtual properties on my entity was causing a cyclical dependency error that was not being detected on the server. By adding the [ScriptIgnore] attribute on the virtual properties, the problem was fixed.

Instead of using the ScriptIgnore attribute, it would probably be better to just return a DTO.

answered Mar 24, 2016 at 22:31

Daryl's user avatar

DarylDaryl

6101 gold badge7 silver badges16 bronze badges

If nothing makes sense, this error can also be caused by PHP Error that is embedded inside html/javascript, such as the one below

<br />
<b>Deprecated</b>:  mysql_connect(): The mysql extension is deprecated and will be removed in the future: use mysqli or PDO instead in <b>C:Projectsrwpdemoensuperge.php</b> on line <b>54</b><br />
var zNodes =[{ id:1, pId:0, name:"ACE", url: "/ace1.php", target:"_self", open:true}

Not the <br /> etc in the code that are inserted into html by PHP is causing the error. To fix this kind of error (suppress warning), used this code in the start

error_reporting(E_ERROR | E_PARSE);

To view, right click on page, «view source» and then examine complete html to spot this error.

answered Nov 9, 2018 at 19:45

Hammad Khan's user avatar

Hammad KhanHammad Khan

16k16 gold badges111 silver badges134 bronze badges

«Uncaught SyntaxError: Unexpected token» error appearance when your data return wrong json format, in some case, you don’t know you got wrong json format.
please check it with alert(); function

onSuccess : function(resp){  
   alert(resp);  
}

your message received should be: {«firstName»:»John», «lastName»:»Doe»}
and then you can use code below

onSuccess : function(resp){  
   var j = JSON.decode(resp); // but in my case i'm using: JSON.parse(resp); 
}

with out error «Uncaught SyntaxError: Unexpected token«
but if you get wrong json format
ex:

…{«firstName»:»John», «lastName»:»Doe»}

or

Undefined variable: errCapt in .... on line<b>65</b><br/>{"firstName":"John", "lastName":"Doe"}

so that you got wrong json format, please fix it before you JSON.decode or JSON.parse

answered Mar 17, 2015 at 10:11

Rain's user avatar

RainRain

6016 silver badges10 bronze badges

1

This happened to because I have a rule setup in my express server to route any 404 back to /# plus whatever the original request was. Allowing the angular router/js to handle the request. If there’s no js route to handle that path, a request to /#/whatever is made to the server, which is just a request for /, the entire webpage.

So for example if I wanted to make a request for /correct/somejsfile.js but I miss typed it to /wrong/somejsfile.js the request is made to the server. That location/file does not exist, so the server responds with a 302 location: /#/wrong/somejsfile.js. The browser happily follows the redirect and the entire webpage is returned. The browser parses the page as js and you get

Uncaught SyntaxError: Unexpected token <

So to help find the offending path/request look for 302 requests.

Hope that helps someone.

answered Jan 26, 2018 at 21:14

Jerinaw's user avatar

JerinawJerinaw

5,1107 gold badges39 silver badges52 bronze badges

I had the same problem and it turned out that the Json returned from the server
wasn’t valid Json-P. If you don’t use the call as a crossdomain call use regular Json.

Community's user avatar

answered Nov 13, 2013 at 8:31

jakob's user avatar

jakobjakob

5,9817 gold badges62 silver badges103 bronze badges

1

My mistake was forgetting single/double quotation around url in javascript:

so wrong code was:

window.location = https://google.com;

and correct code:

window.location = "https://google.com";

answered Apr 11, 2020 at 8:03

Saeed Arianmanesh's user avatar

In my case putting / at the beginning of the src of scripts or href of stylesheets solved the issue.

answered Jul 1, 2021 at 13:02

Vahid Kiani's user avatar

1

I got this error because I was missing the type attribute in script tag.

Initially I was using but when I added the type attribute inside the script tag then my issue is resolved

answered Jul 28, 2022 at 15:37

Hemant 's user avatar

Hemant Hemant

855 bronze badges

I got a «SyntaxError: Unexpected token I» when I used jQuery.getJSON() to try to de-serialize a floating point value of Infinity, encoded as INF, which is illegal in JSON.

answered Jul 18, 2013 at 19:52

Mark Cidade's user avatar

Mark CidadeMark Cidade

97.8k31 gold badges222 silver badges236 bronze badges

1

In my case i ran into the same error, while running spring mvc application due to wrong mapping in my mvc controller

@RequestMapping(name="/private/updatestatus")

i changed the above mapping to

 @RequestMapping("/private/updatestatus")

or

 @RequestMapping(value="/private/updatestatus",method = RequestMethod.GET)

answered Sep 26, 2015 at 3:58

Shravan Ramamurthy's user avatar

For me the light bulb went on when I viewed the source to the page inside the Chrome browser. I had an extra bracket in an if statement. You’ll immediately see the red circle with a cross in it on the failing line. It’s a rather unhelpful error message, because the the Uncaught Syntax Error: Unexpected token makes no reference to a line number when it first appears in the console of Chrome.

answered Jun 21, 2017 at 13:47

JGFMK's user avatar

JGFMKJGFMK

8,1354 gold badges53 silver badges92 bronze badges

I did Wrong in this

   `var  fs = require('fs');
    var fs.writeFileSync(file, configJSON);`

Already I intialized the fs variable.But again i put var in the second line.This one also gives that kind of error…

answered Jul 21, 2017 at 6:13

Janen R's user avatar

Janen RJanen R

72910 silver badges20 bronze badges

For those experiencing this in AngularJs 1.4.6 or similar, my problem was with angular not finding my template because the file at the templateUrl (path) I provided couldn’t be found. I just had to provide a reachable path and the problem went away.

answered Feb 2, 2018 at 5:08

lwdthe1's user avatar

lwdthe1lwdthe1

7771 gold badge12 silver badges12 bronze badges

1

In my case it was a mistaken url (not existing), so maybe your ‘send’ in second line should be other…

answered Dec 20, 2018 at 18:01

Michal - wereda-net's user avatar

This error might also mean a missing colon or : in your code.

answered Oct 6, 2020 at 10:15

Cons Bulaquena's user avatar

Cons BulaquenaCons Bulaquena

2,0432 gold badges26 silver badges24 bronze badges

Facing JS issues repetitively I am working on a Ckeditor apply on my xblock package. please suggest to me if anyone helping me out. Using OpenEdx, Javascript, xblock

xblock.js:158 SyntaxError: Unexpected token '=>'
at eval (<anonymous>)
at Function.globalEval (jquery.js:343)
at domManip (jquery.js:5291)
at jQuery.fn.init.append (jquery.js:5431)
at child.loadResource (xblock.js:236)
at applyResource (xblock.js:199)
at Object.<anonymous> (xblock.js:202)
at fire (jquery.js:3187)
at Object.add [as done] (jquery.js:3246)
at applyResource (xblock.js:201) "SyntaxError: Unexpected token '=>'n    at eval (<anonymous>)n    at Function.globalEval (http://localhost:18010/static/studio/common/js/vendor/jquery.js:343:5)n    at domManip (http://localhost:18010/static/studio/common/js/vendor/jquery.js:5291:15)n    at jQuery.fn.init.append (http://localhost:18010/static/studio/common/js/vendor/jquery.js:5431:10)n    at child.loadResource (http://localhost:18010/static/studio/bundles/commons.js:5091:27)n    at applyResource (http://localhost:18010/static/studio/bundles/commons.js:5054:36)n    at Object.<anonymous> (http://localhost:18010/static/studio/bundles/commons.js:5057:25)n    at fire (http://localhost:18010/static/studio/common/js/vendor/jquery.js:3187:31)n    at Object.add [as done] (http://localhost:18010/static/studio/common/js/vendor/jquery.js:3246:7)n    at applyResource (http://localhost:18010/static/studio/bundles/commons.js:5056:29)"

answered Nov 13, 2021 at 18:47

Neeraj Kumar's user avatar

Late to the party but my solution was to specify the dataType as json. Alternatively make sure you do not set jsonp: true.

answered May 9, 2022 at 9:17

Karim Tingdis's user avatar

Try this to ignore this issue:

Cypress.on('uncaught:exception', (err, runnable) => {
        return false;
    });

answered Sep 9, 2022 at 11:17

Sudheer Singh's user avatar

Uncaught SyntaxError: Unexpected token }

Chrome gaved me the error for this sample code:

<div class="file-square" onclick="window.location = " ?dir=zzz">
    <div class="square-icon"></div>
    <div class="square-text">zzz</div>
</div>

and solved it fixing the onclick to be like

... onclick="window.location = '?dir=zzz'" ...

But the error has nothing to do with the problem..

answered Sep 24, 2013 at 9:21

ungalcrys's user avatar

ungalcrysungalcrys

5,0962 gold badges38 silver badges23 bronze badges

1

I am running an AJAX call in my MooTools script, this works fine in Firefox but in Chrome I am getting a Uncaught SyntaxError: Unexpected token : error, I cannot determine why. Commenting out code to determine where the bad code is yields nothing, I am thinking it may be a problem with the JSON being returned. Checking in the console I see the JSON returned is this:

{"votes":47,"totalvotes":90}

I don’t see any problems with it, why would this error occur?

vote.each(function(e){
  e.set('send', {
    onRequest : function(){
      spinner.show();
    },
    onComplete : function(){
      spinner.hide();
    },
    onSuccess : function(resp){
      var j = JSON.decode(resp);
      if (!j) return false;
      var restaurant = e.getParent('.restaurant');
      restaurant.getElements('.votes')[0].set('html', j.votes + " vote(s)");
      $$('#restaurants .restaurant').pop().set('html', "Total Votes: " + j.totalvotes);
      buildRestaurantGraphs();
    }
  });

  e.addEvent('submit', function(e){
    e.stop();
    this.send();
  });
});

asked Jun 29, 2010 at 18:37

trobrock's user avatar

trobrocktrobrock

46k11 gold badges38 silver badges45 bronze badges

6

Seeing red errors

Uncaught SyntaxError: Unexpected token <

in your Chrome developer’s console tab is an indication of HTML in the response body.

What you’re actually seeing is your browser’s reaction to the unexpected top line <!DOCTYPE html> from the server.

miken32's user avatar

miken32

41.1k16 gold badges106 silver badges148 bronze badges

answered Oct 28, 2014 at 17:56

andy magoon's user avatar

andy magoonandy magoon

2,8512 gold badges19 silver badges14 bronze badges

9

Just an FYI for people who might have the same problem — I just had to make my server send back the JSON as application/json and the default jQuery handler worked fine.

answered Aug 28, 2010 at 20:19

Edward Abrams's user avatar

Edward AbramsEdward Abrams

8851 gold badge6 silver badges3 bronze badges

5

This has just happened to me, and the reason was none of the reasons above. I was using the jQuery command getJSON and adding callback=? to use JSONP (as I needed to go cross-domain), and returning the JSON code {"foo":"bar"} and getting the error.

This is because I should have included the callback data, something like jQuery17209314005577471107_1335958194322({"foo":"bar"})

Here is the PHP code I used to achieve this, which degrades if JSON (without a callback) is used:

$ret['foo'] = "bar";
finish();

function finish() {
    header("content-type:application/json");
    if ($_GET['callback']) {
        print $_GET['callback']."(";
    }
    print json_encode($GLOBALS['ret']);
    if ($_GET['callback']) {
        print ")";
    }
    exit; 
}

Hopefully that will help someone in the future.

answered May 2, 2012 at 11:35

Grim...'s user avatar

Grim…Grim…

16.3k7 gold badges42 silver badges60 bronze badges

3

I have just solved the problem. There was something causing problems with a standard Request call, so this is the code I used instead:

vote.each(function(element){                
  element.addEvent('submit', function(e){
    e.stop();
    new Request.JSON({
      url : e.target.action, 
      onRequest : function(){
        spinner.show();
      },
      onComplete : function(){
        spinner.hide();
      },
      onSuccess : function(resp){
        var j = resp;
        if (!j) return false;
        var restaurant = element.getParent('.restaurant');
        restaurant.getElements('.votes')[0].set('html', j.votes + " vote(s)");
        $$('#restaurants .restaurant').pop().set('html', "Total Votes: " + j.totalvotes);
        buildRestaurantGraphs();
      }
    }).send(this);
  });
});

If anyone knows why the standard Request object was giving me problems I would love to know.

answered Jun 30, 2010 at 20:27

trobrock's user avatar

trobrocktrobrock

46k11 gold badges38 silver badges45 bronze badges

6

I thought I’d add my issue and resolution to the list.

I was getting: Uncaught SyntaxError: Unexpected token < and the error was pointing to this line in my ajax success statement:

var total = $.parseJSON(response);

I later found that in addition to the json results, there was HTML being sent with the response because I had an error in my PHP. When you get an error in PHP you can set it to warn you with huge orange tables and those tables were what was throwing off the JSON.

I found that out by just doing a console.log(response) in order to see what was actually being sent. If it’s an issue with the JSON data, just try to see if you can do a console.log or some other statement that will allow you to see what is sent and what is received.

answered Dec 19, 2013 at 2:50

Keven's user avatar

KevenKeven

3,92114 gold badges57 silver badges77 bronze badges

2

When you request your JSON file, server returns JavaScript Content-Type header (text/javascript) instead of JSON (application/json).

According to MooTools docs:

Responses with javascript content-type will be evaluated automatically.

In result MooTools tries to evaluate your JSON as JavaScript, and when you try to evaluate such JSON:

{"votes":47,"totalvotes":90}

as JavaScript, parser treats { and } as a block scope instead of object notation. It is the same as evaluating following «code»:

"votes":47,"totalvotes":90

As you can see, : is totally unexpected there.

The solution is to set correct Content-Type header for the JSON file. If you save it with .json extension, your server should do it by itself.

answered Dec 29, 2015 at 14:38

Michał Perłakowski's user avatar

It sounds like your response is being evaluated somehow. This gives the same error in Chrome:

var resp = '{"votes":47,"totalvotes":90}';
eval(resp);

This is due to the braces ‘{…}’ being interpreted by javascript as a code block and not an object literal as one might expect.

I would look at the JSON.decode() function and see if there is an eval in there.

Similar issue here:
Eval() = Unexpected token : error

Community's user avatar

answered Aug 13, 2015 at 19:39

Zectbumo's user avatar

ZectbumoZectbumo

3,6501 gold badge30 silver badges24 bronze badges

This happened to me today as well. I was using EF and returning an Entity in response to an AJAX call. The virtual properties on my entity was causing a cyclical dependency error that was not being detected on the server. By adding the [ScriptIgnore] attribute on the virtual properties, the problem was fixed.

Instead of using the ScriptIgnore attribute, it would probably be better to just return a DTO.

answered Mar 24, 2016 at 22:31

Daryl's user avatar

DarylDaryl

6101 gold badge7 silver badges16 bronze badges

If nothing makes sense, this error can also be caused by PHP Error that is embedded inside html/javascript, such as the one below

<br />
<b>Deprecated</b>:  mysql_connect(): The mysql extension is deprecated and will be removed in the future: use mysqli or PDO instead in <b>C:Projectsrwpdemoensuperge.php</b> on line <b>54</b><br />
var zNodes =[{ id:1, pId:0, name:"ACE", url: "/ace1.php", target:"_self", open:true}

Not the <br /> etc in the code that are inserted into html by PHP is causing the error. To fix this kind of error (suppress warning), used this code in the start

error_reporting(E_ERROR | E_PARSE);

To view, right click on page, «view source» and then examine complete html to spot this error.

answered Nov 9, 2018 at 19:45

Hammad Khan's user avatar

Hammad KhanHammad Khan

16k16 gold badges111 silver badges134 bronze badges

«Uncaught SyntaxError: Unexpected token» error appearance when your data return wrong json format, in some case, you don’t know you got wrong json format.
please check it with alert(); function

onSuccess : function(resp){  
   alert(resp);  
}

your message received should be: {«firstName»:»John», «lastName»:»Doe»}
and then you can use code below

onSuccess : function(resp){  
   var j = JSON.decode(resp); // but in my case i'm using: JSON.parse(resp); 
}

with out error «Uncaught SyntaxError: Unexpected token«
but if you get wrong json format
ex:

…{«firstName»:»John», «lastName»:»Doe»}

or

Undefined variable: errCapt in .... on line<b>65</b><br/>{"firstName":"John", "lastName":"Doe"}

so that you got wrong json format, please fix it before you JSON.decode or JSON.parse

answered Mar 17, 2015 at 10:11

Rain's user avatar

RainRain

6016 silver badges10 bronze badges

1

This happened to because I have a rule setup in my express server to route any 404 back to /# plus whatever the original request was. Allowing the angular router/js to handle the request. If there’s no js route to handle that path, a request to /#/whatever is made to the server, which is just a request for /, the entire webpage.

So for example if I wanted to make a request for /correct/somejsfile.js but I miss typed it to /wrong/somejsfile.js the request is made to the server. That location/file does not exist, so the server responds with a 302 location: /#/wrong/somejsfile.js. The browser happily follows the redirect and the entire webpage is returned. The browser parses the page as js and you get

Uncaught SyntaxError: Unexpected token <

So to help find the offending path/request look for 302 requests.

Hope that helps someone.

answered Jan 26, 2018 at 21:14

Jerinaw's user avatar

JerinawJerinaw

5,1107 gold badges39 silver badges52 bronze badges

I had the same problem and it turned out that the Json returned from the server
wasn’t valid Json-P. If you don’t use the call as a crossdomain call use regular Json.

Community's user avatar

answered Nov 13, 2013 at 8:31

jakob's user avatar

jakobjakob

5,9817 gold badges62 silver badges103 bronze badges

1

My mistake was forgetting single/double quotation around url in javascript:

so wrong code was:

window.location = https://google.com;

and correct code:

window.location = "https://google.com";

answered Apr 11, 2020 at 8:03

Saeed Arianmanesh's user avatar

In my case putting / at the beginning of the src of scripts or href of stylesheets solved the issue.

answered Jul 1, 2021 at 13:02

Vahid Kiani's user avatar

1

I got this error because I was missing the type attribute in script tag.

Initially I was using but when I added the type attribute inside the script tag then my issue is resolved

answered Jul 28, 2022 at 15:37

Hemant 's user avatar

Hemant Hemant

855 bronze badges

I got a «SyntaxError: Unexpected token I» when I used jQuery.getJSON() to try to de-serialize a floating point value of Infinity, encoded as INF, which is illegal in JSON.

answered Jul 18, 2013 at 19:52

Mark Cidade's user avatar

Mark CidadeMark Cidade

97.8k31 gold badges222 silver badges236 bronze badges

1

In my case i ran into the same error, while running spring mvc application due to wrong mapping in my mvc controller

@RequestMapping(name="/private/updatestatus")

i changed the above mapping to

 @RequestMapping("/private/updatestatus")

or

 @RequestMapping(value="/private/updatestatus",method = RequestMethod.GET)

answered Sep 26, 2015 at 3:58

Shravan Ramamurthy's user avatar

For me the light bulb went on when I viewed the source to the page inside the Chrome browser. I had an extra bracket in an if statement. You’ll immediately see the red circle with a cross in it on the failing line. It’s a rather unhelpful error message, because the the Uncaught Syntax Error: Unexpected token makes no reference to a line number when it first appears in the console of Chrome.

answered Jun 21, 2017 at 13:47

JGFMK's user avatar

JGFMKJGFMK

8,1354 gold badges53 silver badges92 bronze badges

I did Wrong in this

   `var  fs = require('fs');
    var fs.writeFileSync(file, configJSON);`

Already I intialized the fs variable.But again i put var in the second line.This one also gives that kind of error…

answered Jul 21, 2017 at 6:13

Janen R's user avatar

Janen RJanen R

72910 silver badges20 bronze badges

For those experiencing this in AngularJs 1.4.6 or similar, my problem was with angular not finding my template because the file at the templateUrl (path) I provided couldn’t be found. I just had to provide a reachable path and the problem went away.

answered Feb 2, 2018 at 5:08

lwdthe1's user avatar

lwdthe1lwdthe1

7771 gold badge12 silver badges12 bronze badges

1

In my case it was a mistaken url (not existing), so maybe your ‘send’ in second line should be other…

answered Dec 20, 2018 at 18:01

Michal - wereda-net's user avatar

This error might also mean a missing colon or : in your code.

answered Oct 6, 2020 at 10:15

Cons Bulaquena's user avatar

Cons BulaquenaCons Bulaquena

2,0432 gold badges26 silver badges24 bronze badges

Facing JS issues repetitively I am working on a Ckeditor apply on my xblock package. please suggest to me if anyone helping me out. Using OpenEdx, Javascript, xblock

xblock.js:158 SyntaxError: Unexpected token '=>'
at eval (<anonymous>)
at Function.globalEval (jquery.js:343)
at domManip (jquery.js:5291)
at jQuery.fn.init.append (jquery.js:5431)
at child.loadResource (xblock.js:236)
at applyResource (xblock.js:199)
at Object.<anonymous> (xblock.js:202)
at fire (jquery.js:3187)
at Object.add [as done] (jquery.js:3246)
at applyResource (xblock.js:201) "SyntaxError: Unexpected token '=>'n    at eval (<anonymous>)n    at Function.globalEval (http://localhost:18010/static/studio/common/js/vendor/jquery.js:343:5)n    at domManip (http://localhost:18010/static/studio/common/js/vendor/jquery.js:5291:15)n    at jQuery.fn.init.append (http://localhost:18010/static/studio/common/js/vendor/jquery.js:5431:10)n    at child.loadResource (http://localhost:18010/static/studio/bundles/commons.js:5091:27)n    at applyResource (http://localhost:18010/static/studio/bundles/commons.js:5054:36)n    at Object.<anonymous> (http://localhost:18010/static/studio/bundles/commons.js:5057:25)n    at fire (http://localhost:18010/static/studio/common/js/vendor/jquery.js:3187:31)n    at Object.add [as done] (http://localhost:18010/static/studio/common/js/vendor/jquery.js:3246:7)n    at applyResource (http://localhost:18010/static/studio/bundles/commons.js:5056:29)"

answered Nov 13, 2021 at 18:47

Neeraj Kumar's user avatar

Late to the party but my solution was to specify the dataType as json. Alternatively make sure you do not set jsonp: true.

answered May 9, 2022 at 9:17

Karim Tingdis's user avatar

Try this to ignore this issue:

Cypress.on('uncaught:exception', (err, runnable) => {
        return false;
    });

answered Sep 9, 2022 at 11:17

Sudheer Singh's user avatar

Uncaught SyntaxError: Unexpected token }

Chrome gaved me the error for this sample code:

<div class="file-square" onclick="window.location = " ?dir=zzz">
    <div class="square-icon"></div>
    <div class="square-text">zzz</div>
</div>

and solved it fixing the onclick to be like

... onclick="window.location = '?dir=zzz'" ...

But the error has nothing to do with the problem..

answered Sep 24, 2013 at 9:21

ungalcrys's user avatar

ungalcrysungalcrys

5,0962 gold badges38 silver badges23 bronze badges

1

Неожиданный токен ошибки синтаксического анализа обычно возникает при несовместимости между параметром синтаксического анализатора и кодом. Однако при написании JavaScript разработчики все же сталкиваются с этой ошибкой.

Эта ошибка возникает, когда среда разработки несовместима с возможностями парсера. Сначала мы рассмотрим причины этой ошибки и то, как она часто возникает.

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

Что вызывает ошибку синтаксического анализа неожиданного токена?

При написании приложения JavaScript вы можете получить ошибку, потому что определенный синтаксис отсутствует или добавлен в ваш код. Однако непредвиденная ошибка токена уведомляет вас о том, что JavaScript ожидает определенного порядка в коде, который вы пишете. Пример того, как выглядит непредвиденный токен ошибки синтаксического анализа:

Тем не менее, вы должны понимать, что эта ошибка может возникать по разным причинам. У JavaScript есть ожидания.

Итак, вы должны знать, что такое правила и ожидания JavaScript. Тогда это поможет вам понять, в чем проблема.

Как я могу исправить ошибку синтаксического анализа неожиданного токена?

1. Укажите используемый вами парсер

Для пользователей ESLint необходимо указать парсер для ESLint. Это важно, потому что синтаксический анализатор сможет генерировать совместимый синтаксис JavaScript, который может прочитать ESLint.

Парсер типа babel-eslint подойдет для ESLint. Это связано с тем, что ESLint несовместим с современным синтаксисом JavaScript. Итак, вам нужно указать парсер, который будет использоваться для вашей конфигурации.

В приведенном выше примере синтаксический анализатор специфичен, поэтому ESLint сможет знать, что использовать. Кроме того, делая это, вы больше не получите машинописный текст ESLint с ошибкой синтаксического анализа неожиданного токена.

2. Проверьте правильность пунктуации

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

Итак, чтобы решить проблему с неожиданным токеном, просмотрите свои коды на наличие пунктуационных ошибок. Знаки препинания, такие как круглые скобки и запятые, должны быть правильными в вашем коде. В противном случае JavaScript не распознает его и не сможет проанализировать.

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

3. Проверьте на опечатки

Как было сказано ранее, у JavaScript есть свой синтаксис. Таким образом, его синтаксические анализаторы ожидают, что каждый токен и символ будут в определенном порядке, прежде чем они смогут их прочитать.

Тем не менее, проследите свой код, чтобы узнать, откуда возникла ошибка, и исправьте ее. Редакторы кода могут помочь вам отредактировать синтаксис еще до того, как синтаксический анализатор обнаружит его.

Очень важно знать правила синтаксиса JavaScript и их использование в деталях. Затем, следуя приведенным выше рекомендациям, вы можете исправить ошибку синтаксического анализа и непредвиденную проблему с токеном.

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


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 рядом с неожиданным токеном. Если вы Если вы прочитали всю статью и нашли ее содержание полезным, сообщите нам о своих предложениях и вопросах в разделе комментариев.

Синтаксическая ошибка сообщения об ошибке рядом с неожиданным токеном `(‘ возникает в среде типа Unix, Cygwin и в интерфейсе командной строки в Windows. Эта ошибка, скорее всего, будет вызвана при попытке запустить сценарий оболочки, который был отредактирован или созданный в старых системах DOS / Windows или Mac.

Ошибка синтаксиса рядом с неожиданным токеном `('

Это сообщение об ошибке также появляется, когда вы вводите команды в командной строке Linux для повседневных задач, таких как копирование файлов вручную и т. Д. Основные причины появления этого сообщения об ошибке либо из-за неправильного синтаксиса, либо из-за проблемы ОС при интерпретации команд другой системы / оболочка.

Что вызывает синтаксическую ошибку рядом с неожиданным токеном `(‘?

Причины этого сообщения об ошибке очень разнообразны и не могут быть перечислены в одной статье, так как существуют тысячи возможных ошибок синтаксиса при выполнении команд. Основные причины этой ошибки:

  • Неверный синтаксис при выполнении любой команды на любой платформе. Либо вы неправильно используете команду, либо ввели неправильный синтаксис.
  • Оболочка несовместима между системами Unix / DOS.
  • Возникли проблемы с запуском сценария оболочки bash из другого источника .

В этой статье мы предполагаем, что вы знаете основы программирования и имеете представление о том, что делаете. Если вы новичок, лучше всего следовать подробным инструкциям по языку / команде, которую вы пытаетесь выполнить. Вероятно, вы ошиблись в синтаксисе.

Решение 1. Проверка синтаксиса и формата команд

Первая и основная причина, по которой вы можете получить это сообщение об ошибке, — это неправильный синтаксис в вашем коде или несоблюдение точного формата команд. Каждая команда имеет предопределенный формат, который вы можете увидеть в ее документации. Некоторые параметры являются необязательными, другие — обязательными.

Кроме того, следует уделять особое внимание дополнительному пространству , использованию двойных кавычек и обязательным параметрам. Если какие-либо из них отсутствуют или были объявлены неправильно, вы не сможете выполнить свой код.

Например, вместо следующего кода

[mycom7] # ./ctopo.sh um_test1 [(1,2), (2,1)]

Вам нужно выполнить его как

[mycom7] # ./ctopo.sh um_test1 "[(1,2), (2,1)]"

Также убедитесь, что вы правильно выполняете свои команды / сценарий оболочки, если он занимает несколько строк.

Из-за типа параметра необходимы двойные кавычки. Дополнительное пространство также может испортить ваш код и вызвать сообщение об ошибке. Убедитесь, что вы проверили официальную документацию команды, которую вы выполняете, и посмотрите, есть ли там проблема.

Решение 2. Устранение неполадок сценария оболочки

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

Попробуйте запустить оболочку с параметром vx. Это покажет нам, какие команды выполняются и какие значения хранятся в скрипте. Здесь вы можете устранять неполадки и диагностировать, что не так.

Например, выполните скрипт в терминале после включения vx как:

# sh -vx ./test_script5.sh

Вы можете проверить содержимое скрипта, используя команду cat как:

# cat test_script5.sh

Решение 3. Использование команды dos2unix.exe

В текстовых файлах Windows / DOS новая строка представляет собой комбинацию символа возврата каретки ( r), за которым следует перевод строки ( n). В Mac (до Mac OS X) для переноса строки использовался простой возврат каретки ( r). Unix / Linux и Mac OS X используют перевод строки ( n). Если вы используете Cygwin, он не сможет обработать сценарии, созданные DOS / Windows и более ранними версиями Mac из-за дополнительного символа возврата каретки ( r).

Использование команды dos2unix.exe

Здесь вы можете создать команду ‘dos2unix.exe’, которая преобразует скрипт в правильный формат, а затем вы можете выполнить его без каких-либо проблем.

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

The error message syntax error near unexpected token `(‘ occurs in a Unix-type environment, Cygwin, and in the command-line interface in Windows. This error will most probably be triggered when you try to run a shell script which was edited or created in older DOS/Windows or Mac systems.

Syntax Error near unexpected token `('

Syntax Error near unexpected token `(‘

This error message also surfaces when you are entering commands in the Linux command line for everyday tasks such as copying files manually etc. The main reasons why this error message occurs is either because of bad syntax or problem of the OS in interpreting another system’s commands/shell.

The reasons for this error message are very diverse and cannot be listed in one article as there are thousands of possibilities of syntax going wrong when executing commands. The core reasons for this error are:

  • Bad syntax when executing any command in either platform. Either you are not using the command correctly or have entered the wrong syntax.
  • The shell is not compatible between Unix/DOS systems.
  • There are issues running the bash shell script from another source.

In this article, we assume that you know the basics of coding and have an idea what you are doing. If you are a beginner, it is best that you follow in-depth tutorials of the language/command which you are trying to execute. You probably have made a mistake of some syntax.

Solution 1: Checking Syntax and Format of commands

The first and foremost reason why you might experience this error message is that of bad syntax in your code or you not following the exact format of the commands. Each command has a predefined format which you can see in its documentation. Several parameters are optional which others are mandatory.

Furthermore, extra care should be taken for extra space, use of double quotes, and the mandatory parameters required. If any of them are missing or have been declared incorrectly, you will not be able to execute your code.

For example, instead of the following code

[mycom7] # ./ctopo.sh um_test1 [(1,2),(2,1)]

You need to execute it as

[mycom7] # ./ctopo.sh um_test1 "[(1,2),(2,1)]"

Also, make sure that you are executing your commands/shell script correctly if it is spanning several lines.

Because of the parameter type, the double quotes are necessary. An extra space might also ruin your code and force the error message. Make sure that you check the official documentation of the command you are executing and see if there is a problem there.

Solution 2: Troubleshooting your shell script

If are using a shell script which works in the source system but returns an error in the target, you can troubleshoot the script by checking the variables which are stored during the execution and then see what is causing the issue. This is a very common cause as in several cases, the shell tries to interpret an unprintable character.

Try running the shell with the parameter of ‘vx’. This will show us what commands are being run and what values are stored in the script. Through here you can troubleshoot and diagnose what is going wrong.

For example, execute the script in the terminal after including ‘vx’ as:

# sh -vx ./test_script5.sh

You can check the contents of the script using the ‘cat’ command as:

# cat test_script5.sh

Solution 3: Using ‘dos2unix.exe’ command

In Windows/DOS text files, a new line is a combination of a Carriage Return (r) followed by a Line Feed (n). In Mac (before Mac OS X), a line break used a simple Carriage Return (r). Unix/Linux and Mac OS X use Line Feed (n) line breaks. If you are using Cygwin, it will fail to process the scripts made by DOS/Windows and older Mac because of the extra Carriage Return (r) character.

Using 'dos2unix.exe' command

Using ‘dos2unix.exe’ command

Here you can make of ‘dos2unix.exe’ command which will convert the script to the correct format and then you can execute it without any issues.

To conclude, you need research your commands and type of platform you are using and make sure there are not any discrepancies. Since we cannot cover each and every possibility, you would have an idea what kinds of errors can occur and how to fix them.

Photo of Kevin Arrows

Kevin Arrows

Kevin is a dynamic and self-motivated information technology professional, with a Thorough knowledge of all facets pertaining to network infrastructure design, implementation and administration. Superior record of delivering simultaneous large-scale mission critical projects on time and under budget.

I am trying to download flareget download manager via wget
I get error

wget  http://www.flareget.com/files/flareget/debs/amd64/flareget_2.3-24_amd64(stable)_deb.tar.gz
bash: syntax error near unexpected token `('

Why is that error coming and what is the solution for that?

asked Nov 8, 2013 at 10:27

Registered User's user avatar

Registered UserRegistered User

4,7349 gold badges35 silver badges43 bronze badges

1

You should use single quotes ' or double quotes " around the URL in this case (and in general):

wget  'http://www.flareget.com/files/flareget/debs/amd64/flareget_2.3-24_amd64(stable)_deb.tar.gz'

From now, you should use this method in general when you use a string which contain parentheses as argument in a command. That is because parentheses are used for grouping by the shell such that they are not communicated in any way to a command. So, the bash shell will give you a syntax error:

$ echo some (parentheses)
bash: syntax error near unexpected token `('
$ echo 'some (parentheses)'
some (parentheses)

answered Nov 8, 2013 at 10:30

Radu Rădeanu's user avatar

Radu RădeanuRadu Rădeanu

164k47 gold badges321 silver badges397 bronze badges

1

It’s because of the brackets. You need to escape them like this:

wget  http://www.flareget.com/files/flareget/debs/amd64/flareget_2.3-24_amd64(stable)_deb.tar.gz

Now it should work.

answered Nov 8, 2013 at 10:29

chaos's user avatar

2

Mine had nothing to do with un-escaped brackets and everything to do with an alias already being defined with the same name as the function.

Alias in one file:

alias foo="echo do something"

Function in another:

foo() {
    # Do something else
}

Both of these files were sourced by my ~/.bashrc, giving me the unhelpful error message:

syntax error near unexpected token (

Zanna's user avatar

Zanna

68.3k55 gold badges210 silver badges320 bronze badges

answered Nov 29, 2021 at 2:09

Andy J's user avatar

Andy JAndy J

1,0181 gold badge12 silver badges17 bronze badges

1

Синтаксическая ошибка:Неожиданный знак

Исключения JavaScript «неожиданный токен» возникают,когда ожидалась определенная языковая конструкция,но было предоставлено что-то другое.Это может быть простая опечатка.

Message

SyntaxError: expected expression, got "x"
SyntaxError: expected property name, got "x"
SyntaxError: expected target, got "x"
SyntaxError: expected rest argument name, got "x"
SyntaxError: expected closing parenthesis, got "x"
SyntaxError: expected '=>' after argument list, got "x"

Error type

Что пошло не так?

Ожидалось,что будет определенная языковая конструкция,но было предоставлено кое-что еще.Это может быть простая опечатка.

Examples

Expression expected

Например,при цепочечных выражениях трейлинговые запятые не допускаются.

for (let i = 0; i < 5,; ++i) {
  console.log(i);
}

Правильным было бы опустить запятую или добавить другое выражение:

for (let i = 0; i < 5; ++i) {
  console.log(i);
}

Недостаточно скобок

Иногда вы опускаете скобки вокруг операторов if :

function round(n, upperBound, lowerBound) {
  if (n > upperBound) || (n < lowerBound) { 
    throw new Error(`Number ${n} is more than ${upperBound} or less than ${lowerBound}`);
  } else if (n < (upperBound + lowerBound) / 2) {
    return lowerBound;
  } else {
    return upperBound;
  }
} 

Поначалу скобки могут выглядеть правильно, но обратите внимание на то, как || находится вне скобок. Правильно было бы заключить в скобки || :

function round(n, upperBound, lowerBound) {
  if ((n > upperBound) || (n < lowerBound)) {
    throw new Error(`Number ${n} is more than ${upperBound} or less than ${lowerBound}`);
  } else if (n < (upperBound + lowerBound) / 2) {
    return lowerBound;
  } else {
    return upperBound;
  }
}

See also

  • SyntaxError


JavaScript

  • ReferenceError: присвоение необъявленной переменной «x»

    Исключение только для строгого режима JavaScript «Присвоение необъявленной переменной» возникает, когда значение ReferenceError было присвоено только в строгом режиме.

  • ReferenceError: ссылка на неопределенное свойство «x»

    Предупреждение JavaScript «ссылка на неопределенное свойство» возникает при попытке доступа к несуществующему объекту.

  • TypeError: «x» (не) «y»

    Исключение JavaScript «(не)y» возникает, когда был непредвиденный тип.

  • SyntaxError:оператор функции требует имени

    Исключение JavaScript «оператор функции требует имени» возникает, когда в коде есть оператор функции, требующий имени.

Понравилась статья? Поделить с друзьями:
  • Некст рп ошибка при запуске
  • Неошибка или не ошибка
  • Неправильное окончание это орфографическая ошибка
  • Некст рп ошибка cd46
  • Неотъемлемым атрибутом современного студента является ноутбук лексическая ошибка