Syntax error near unexpected token newline linux

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.

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"

  • Печать

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

Тема: ошибка синтаксиса около неожиданной лексемы `newline’>  (Прочитано 3582 раз)

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

Оффлайн
Артур27

Всем привет! вот такая ошибка вылезла ошибка синтаксиса около неожиданной лексемы `newline’>, как исправить не понимаю, так как неделю всего пользуюсь ноутом, помогите!! крик души


Оффлайн
EvangelionDeath

Артур27, а мы должны угадать где вылезла, в следстии чего и что вы перед этим делали?

HP Pro 840 G3: Intel i5-6300U, 32GB DDR4 2133MHz, Intel 520, Intel Pro 2500 180GB/Ubuntu 22.04
Dell Latitude 5590: Intel i5-8350U, 16GB DDR4 2400MHz, Intel 620, Samsung 1TB/Ubuntu 22.04


Оффлайн
Артур27

artur@Inspiron-5570:~$ <sudo app-get install-f>
bash: ошибка синтаксиса около неожиданной лексемы `newline’
artur@Inspiron-5570:~$

В правом верхнем углу вылезло уведомление: Произошла ошибка. Пожалуйста запустите менеджер пакетов или введите команду в терминале sudo app-get install-f.
наверху пример, ввожу и получаю такую ошибку


Оффлайн
ALiEN175

скобки уберите

и не app-get, a apt-get
и пробел после install где?

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


Оффлайн
Azure

Артур27, странный какой-то пример… Может надо так?

artur@Inspiron-5570:~$ sudo apt-get install -f

В Линукс можно сделать ВСЁ что угодно, достаточно знать КАК !


Оффлайн
Артур27

Блин вот я тупил… спасибо! Все верно сказано


  • Печать

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

If while opening your bash you get an error message like «syntax error near unexpected token `newline'», this is because now your gentoo bash reads the .bashrc file originally from ubuntu. Check the line that is complaining by editing or commenting it, or create a new gentoo-based .bashrc file and you won’t see the message anymore. Below I copy-pasted a working .bashrc file for gentoo.

# /etc/bash/bashrc
#
# This file is sourced by all *interactive* bash shells on startup,
# including some apparently interactive shells such as scp and rcp
# that can't tolerate any output.  So make sure this doesn't display
# anything or bad things will happen !


# Test for an interactive shell.  There is no need to set anything
# past this point for scp and rcp, and it's important to refrain from
# outputting anything in those cases.
if [[ $- != *i* ]] ; then
        # Shell is non-interactive.  Be done now!
        return
fi

# Bash won't get SIGWINCH if another process is in the foreground.
# Enable checkwinsize so that bash will check the terminal size when
# it regains control.  #65623
# http://cnswww.cns.cwru.edu/~chet/bash/FAQ (E11)
shopt -s checkwinsize

# Disable completion when the input buffer is empty.  i.e. Hitting tab
# and waiting a long time for bash to expand all of $PATH.
shopt -s no_empty_cmd_completion

# Enable history appending instead of overwriting when exiting.  #139609
shopt -s histappend

# Save each command to the history file as it's executed.  #517342
# This does mean sessions get interleaved when reading later on, but this
# way the history is always up to date.  History is not synced across live
# sessions though; that is what `history -n` does.
# Disabled by default due to concerns related to system recovery when $HOME
# is under duress, or lives somewhere flaky (like NFS).  Constantly syncing
# the history will halt the shell prompt until it's finished.
#PROMPT_COMMAND='history -a'

# Change the window title of X terminals
case ${TERM} in
        [aEkx]term*|rxvt*|gnome*|konsole*|interix)
                PS1='[33]0;u@h:w07]'
                ;;
        screen*)
                PS1='[33ku@h:w33\]'
                ;;
        *)
                unset PS1
                ;;
esac

# Set colorful PS1 only on colorful terminals.
# dircolors --print-database uses its own built-in database
# instead of using /etc/DIR_COLORS.  Try to use the external file
# first to take advantage of user additions.
use_color=false
if type -P dircolors >/dev/null ; then
        # Enable colors for ls, etc.  Prefer ~/.dir_colors #64489
        LS_COLORS=
        if [[ -f ~/.dir_colors ]] ; then
                # If you have a custom file, chances are high that it's not the default.
                used_default_dircolors="no"
                eval "$(dircolors -b ~/.dir_colors)"
        elif [[ -f /etc/DIR_COLORS ]] ; then
                # People might have customized the system database.
                used_default_dircolors="maybe"
                eval "$(dircolors -b /etc/DIR_COLORS)"
        else
                used_default_dircolors="yes"
                eval "$(dircolors -b)"
        fi
        if [[ -n ${LS_COLORS:+set} ]] ; then
                use_color=true
        fi
        unset used_default_dircolors
else
        # Some systems (e.g. BSD & embedded) don't typically come with
        # dircolors so we need to hardcode some terminals in here.
        case ${TERM} in
        [aEkx]term*|rxvt*|gnome*|konsole*|screen|cons25|*color) use_color=true;;
        esac
fi

if ${use_color} ; then
        if [[ ${EUID} == 0 ]] ; then
                PS1+='[33[01;31m]h[33[01;34m] W $[33[00m] '
        else
                PS1+='[33[01;32m]u@h[33[01;34m] w $[33[00m] '
        fi

        alias ls='ls --color=auto'
        alias grep='grep --colour=auto'
        alias egrep='egrep --colour=auto'
        alias fgrep='fgrep --colour=auto'
else
        if [[ ${EUID} == 0 ]] ; then
                # show root@ when we don't have colors
                PS1+='u@h W $ '
        else
                PS1+='u@h w $ '
        fi
fi

for sh in /etc/bash/bashrc.d/* ; do
        [[ -r ${sh} ]] && source "${sh}"
done

# Try to keep environment pollution down, EPA loves us.
unset use_color sh
  • Home
  • Forum
  • The Ubuntu Forum Community
  • Ubuntu Official Flavours Support
  • New to Ubuntu
  • [SOLVED] bash: syntax error near unexpected token `newline’

  1. bash: syntax error near unexpected token `newline’

    Hello all. I’m running Ubuntu Server and am having problems running a .sh script trying to build a Open GTS Server.

    the command is

    bin/initdb.sh -rootUser=<rootUser> -rootPass=<rootPass>

    The script is supposed to create a new mysql database. When i run the command i get..

    -bash: syntax error near unexpected token `newline’

    I’ve tried running it as sudo and my user and i get the same thing.

    tia


  2. Re: bash: syntax error near unexpected token `newline’

    do root user or password contain the sequence n ?


  3. Re: bash: syntax error near unexpected token `newline’

    Quote Originally Posted by DaithiF
    View Post

    do root user or password contain the sequence n ?

    No, there’s an n but no n in the rootUser / rootPass and just to be certain i changed the mysql root password to something without an n and got the same error.


  4. Re: bash: syntax error near unexpected token `newline’

    Hmm … ok, wild guess, when it says

    Code:

    bin/initdb.sh -rootUser=<rootUser> -rootPass=<rootPass>

    are you typing:

    Code:

    bin/initdb.sh -rootUser=<rootUser> -rootPass=<rootPass>

    or

    Code:

    bin/initdb.sh -rootUser=rootUser -rootPass=rootPass

    (its the second one that you need — the angle brackets are there as placeholders, they’re not meant to be typed)


  5. Re: bash: syntax error near unexpected token `newline’

    Quote Originally Posted by DaithiF
    View Post

    Hmm … ok, wild guess, when it says

    Code:

    bin/initdb.sh -rootUser=<rootUser> -rootPass=<rootPass>

    are you typing:

    Code:

    bin/initdb.sh -rootUser=<rootUser> -rootPass=<rootPass>

    or

    Code:

    bin/initdb.sh -rootUser=rootUser -rootPass=rootPass

    (its the second one that you need — the angle brackets are there as placeholders, they’re not meant to be typed)

    doh! taking out the angle brackets did it.

    thanks!


  6. Smile Re: bash: syntax error near unexpected token `newline’


Bookmarks

Bookmarks


Posting Permissions

Понравилась статья? Поделить с друзьями:
  • Syntax error near unexpected token elif
  • Syntax error near unexpected token done bash
  • Syntax error missing parentheses in call to print ошибка
  • Syntax error missing operator in query expression
  • Syntax error last token seen t garbled time