6 Fixes For “syntax error near unexpected token”

What is it?

This problem (syntax error near unexpected token) usually occurs in Cygwin, a Unix-type of environment and command-line interface for Microsoft Windows.

 

It will be triggered when you try to run a shell script which has been created or edited in the older Mac systems or Windows/DOS.

In Windows/DOS text files, a new line is usually the combination of two characters including a Carriage Return (r) which is followed by a Line Feed (n) character.

Prior to Mac OS X in Mac systems, a line break used to be the single Carriage Return (r) character. Modern Mac OS & Linux or Unix systems make use of the Unix style Line Feed (n) line breaks.

Cygwin might fail to process the available scripts that are formatted in Old Mac OS or Windows/DOS systems because of the presence of the extra Carriage Return (r) character.

How to Fix The “Syntax Error Near Unexpected Token” Error?

First Fix: Use The “dos2unix.exe” Command

To solve the problem of the error “syntax error near unexpected token”, the users are recommended to make use of the “dos2unix.exe” command.

This command will be useful in converting the script to the Unix readable format.

 

Second Fix: Use The “cat” Command

If you are making use of a Linux system, then you can follow the steps:

  1. Make use of the “cat” command for displaying the contents of the script.
  2. Then, you can utilize the commands of copy & paste for copying what was displayed. Paste the copied content on a new file. The new file would visually appear to be similar as the old one. However, it will no longer contain the non-printable characters and will remove the errors.
  3. Set the permissions on the file that has been newly created such that it can be executed.
  4. Run the new script by using the “sh –vx