How to fix the “syntax error near unexpected token `newline'” error

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.

Resolve the “syntax error near unexpected token `newline'” problem

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.

Top 10 Linux Distros

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.