Line 1 syntax error near unexpected token newline

Oftentimes when we are using Bash scripting or the git add command, we can run into this error “syntax error near unexpected token `newline'. What exactly does this code mean?...

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

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

Reason 1: Bash Scripting 

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

$ cat <bash-script>

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

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

$ cat samplefile.sh

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


Solution

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

Use of “< >” in strings

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

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

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

Reason 2: “git add” command

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

Solution: Remove Brackets

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

Conclusion

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

@ajay-aravind

go version go1.10.2 darwin/amd64

git rev-parse HEAD
cb46983

When I tried to run server program which is having just only two paths and a dummy server I am getting below error

./server ./server: line 1: syntax error near unexpected token newline’
./server: line 1: !’`

Please help me resolve the problem.

@elithrar

@ajay-aravind

package http_muxer

import (
«log»
«net/http»

)

func main() {
r := mux.NewRouter()
r.HandleFunc(«/», HomeHandler)
// r.HandleFunc(«/products», ProductsHandler)
// r.HandleFunc(«/articles», ArticlesHandler)
http.Handle(«/», r)
log.Fatal(http.ListenAndServe(«:8000», r))
}

func HomeHandler(w http.ResponseWriter, request *http.Request) {
w.Write([]byte(«Got request on /»))
}

// func ProductsHandler(responce http.ResponseWriter, request *http.Request) {
// responce.Write([]byte(«Got a request on /products»))
// }
// func ArticlesHandler(responce http.ResponseWriter, request *http.Request) {
// responce.Write([]byte(«Got a request on /articles»))
// }

@elithrar

Your package should be `package main` if it has a main() function.

On Mon, Jun 11, 2018 at 12:23 AM ajay-aravind ***@***.***> wrote:
package http_muxer

import (
«log»
«net/http»

«github.com/gorilla/mux»

)

func main() {
r := mux.NewRouter()
r.HandleFunc(«/», HomeHandler)
// r.HandleFunc(«/products», ProductsHandler)
// r.HandleFunc(«/articles», ArticlesHandler)
http.Handle(«/», r)
log.Fatal(http.ListenAndServe(«:8000», r))
}

func HomeHandler(w http.ResponseWriter, request *http.Request) {
w.Write([]byte(«Got request on /»))
}

// func ProductsHandler(responce http.ResponseWriter, request
*http.Request) {
// responce.Write([]byte(«Got a request on /products»))
// }
// func ArticlesHandler(responce http.ResponseWriter, request
*http.Request) {
// responce.Write([]byte(«Got a request on /articles»))
// }


You are receiving this because you commented.
Reply to this email directly, view it on GitHub
<#388 (comment)>, or mute
the thread
<https://github.com/notifications/unsubscribe-auth/AABIcLO6aR2pvGLS8ENjvmunuyVanMeWks5t7hrcgaJpZM4Uh1IL>
.

@ashar111

Please share your code.

im also getting the same error with this code
/var/www/html/index.html: line 1: syntax error near unexpected token newline' /var/www/html/index.html: line 1:

@elithrar

@ashar111 your error seems unrelated to this package / software.

@UtkarshSaxenautk

package main

import (
«net/http»
«github.com/gorilla/mux»
)
const (
CONN_HOST = «localhost»
CONN_PORT = «3030»
)

var GetHandler = http.HandlerFunc ( func(w http.ResponseWriter ,
r * http.Request){ w.Write([]byte(«Hello World»))} )

var PostHandler = http.HandlerFunc ( func(w http.ResponseWriter ,
r * http.Request){ w.Write([]byte(«It is a post request»))} )

var PathHandler = http.HandlerFunc ( func(w http.ResponseWriter ,
r * http.Request){
vars := mux.Vars(r)
name := vars[«name»]
w.Write([]byte(«Hi» , name))
}
)

func main(){
router := mux.Router()
router.Handle(«/» , GetHandler).Methods(«GET»)
router.Handle(«/post» , PostHandler).Methods(«POST»)
router.Handler(«/hello/{name}» , PathHandler).Methods(«GET» , «POST»)
http.ListenAndServe(CONN_HOST + «:» + CONN_PORT)
}

i have error in this program which is : muxrouter.go:22:50: syntax error: unexpected newline, expecting comma or )

I’m a complete BASH beginner who needs to make sure this script works. It’s supposed to restore an evenstore backup from an azure blob storage. Unfortunately it doesn’t work.

When I run it in ShellCheck:

Line 14:
export AZURE_STORAGE_KEY=<Insert key>
^-- SC1009 (info): The mentioned syntax error was in this simple command.
       ^-- SC1073 (error): Couldn't parse this variable assignment. Fix to allow more checks.
                          ^-- SC1072 (error): Fix any mentioned problems and try again.

When I actually run it :

restore_eventstore.sh: line 14: syntax error near unexpected token `newline'
restore_eventstore.sh: line 14: `export AZURE_STORAGE_KEY=<Insert key>'

I have googled these errors but I was unable to find an answer for my case. Any help appreciated. Here is the script in its entirety:

#!/bin/bash
# Needs azure cli to work.
# Install command: curl -sL https://aka.ms/InstallAzureCLIDeb | sudo bash

backup_name=$1

if [ -z "$backup_name" ]
then
    echo "Must supply an file to use in the restore"
    exit
fi

export AZURE_STORAGE_ACCOUNT=stoclbackups
export AZURE_STORAGE_KEY=<Insert key>

echo "Downloading backup $backup_name from blob storage"
az storage blob download --container-name node1backups --name $backup_name --file $backup_name

if [ ! -s "$backup_name" ]
then
    echo "Failed to download the backup file $backup_name"
    exit
fi

echo "Stopping the eventstore service"
systemctl stop eventstore

if [ -d eventstore_backup ]
then
    echo "Removing old local eventstore backup"
    rm -rf eventstore_backup
fi
echo "Doing an backup of the current db to eventstore_backup"
mkdir eventstore_backup
cp -r db/* eventstore_backup

echo "Removing the old data from eventstore db directory"
rm -rf db/*

echo "Unpacking the backup $backup_name into the eventstore db directory"
tar -zvxf $backup_name -C db/

echo "Truncate the eventstore data to the latest chaser checkpoint"
cp db/chaser.chk db/truncate.chk

echo "Restore is complete. Start the eventstore service with: sudo systemctl start eventstore"

I have set the php file in cron job on the parallel plesk 10.4.4 server.In notification email it is showing the errors.

      syntax error near unexpected token `<' 
     syntax error near unexpected token `newline'
     /newsletter_auto.php: line 2: `<html>'

the code of the newsletter_auto.php file is below

        <title>Market Trend Newsletter</title>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.7.1/jquery.min.js"></script>
<script type="text/javascript">
$(document).ready(function(){
var abc=encodeURIComponent($("#newsletter").html());
    $.ajax({
            type:'POST',
            url:'newsletter_automation.php?abc='+abc,
            success:function(data){
             }
        });
});
</script>
    </head>
    <body>
<?php
    function checkForNULLString($str)
    {
        if($str == "" || $str == " " || $str == "  " || $str == "   " || $str == "    " || $str == "     " || $str == "       " || $str == null)
        {
            return false;
        }
        else 
        {
            return true;
        }
    }

    function cleanForDatabase($str)
    {
        $str =  preg_replace('/[^a-zA-Z0-9s-_#@.,]/', '', $str);
        $str = mysql_real_escape_string($str);

        return $str;
    }

    function runSQLQuery($query,$mysqlConnect)
    {
        $result = mysql_query($query,$mysqlConnect);

        if(mysql_errno($mysqlConnect) != 0){
            echo "n !<u>!ERROR:</u>mysqlConnect:".$mysqlConnect." <br/>query:".$query."<br/> Query.result:" . mysql_errno($mysqlConnect) . ": " . mysql_error($mysqlConnect) . "n";

            //Log the Query Error
            $result = mysql_query($query,$mysqlConnect); exit();

        }

        return($result);
    }

    function insertIconAdminLink($link,$name,$type,$text=NULL,$target="_self")
    {
        //print"<a href="".$link."" onmouseout="Javascript:roll_over_switch('".$name."',false);" onmouseover="Javascript:roll_over_switch('".$name."',true);"><img name="".$name."" id="".$name."" border="0" src="/images/".$type.".gif" />".$text."</a>";

        print" <a class="iconLinkText" href="".$link."" target="".$target.""><img name="".$name."" id="".$name."" border="0" src="/images/".$type.".gif" width="24" height="24" />".$text."</a> ";
    }

    <div id="newsletter"> <p>Stocks traded <?php echo $stock_direction; ?> today with the <?php echo $stock_index; ?> closing at <?php echo $stock_index_close; ?>, <?php echo $stock_direction; ?> <?php echo $stock_index_difference; ?> or <?php echo $stock_index_percentage_difference; ?> from the previous close. The number of NYSE advances were <?php echo $nyse_advances; ?>, the number of decliners was </div>
      </body>
      </html>

Please let me know how can I resolve this?

Понравилась статья? Поделить с друзьями:

Читайте также:

  • Line 0 parsing error cannot read properties of undefined reading map
  • Linde t20 коды ошибок
  • Linalgerror schur decomposition solver error
  • Limit in subquery mysql error
  • Limit in sql syntax error

  • 0 0 голоса
    Рейтинг статьи
    Подписаться
    Уведомить о
    guest

    0 комментариев
    Старые
    Новые Популярные
    Межтекстовые Отзывы
    Посмотреть все комментарии