Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Syntax error near unexpected token `elif'

Tags:

./chkf: line 30: syntax error near unexpected token `elif' '/chkf: line 30: `elif [ -f "$object" ] ; then   if [ -d "$object" ] ; then     message="$message a directory" elif [ -f "$object" ] ; then     message="$message a regular file." else     message="$message not a known file type" fi 

Also this,

./chkf: line 38: syntax error near unexpected token `else' '/chkf: line 38: `else   if [ -w "$object" ] ; then     write="writeable" else      write="not writeable" fi 

What is wrong with this? It seems to be correct. I tried so many variations and cannot figure out what is wrong. Is there some kind of invisible character? If so, is there a command to strip it?

Edit: When I add #!/bin/bash at the top, I get the following error:

interpreter "/bin/bash" not found file link resolves to "/usr/bin/bash" -bash: ./chkf: /bin/bash^M: bad interpreter: No such file or directory 
like image 444
Strawberry Avatar asked Nov 15 '10 07:11

Strawberry


People also ask

How do I fix unexpected token in Unix?

If you execute the code written in the Windows OS in the Cygwin, you may get the Syntax error near unexpected token '('. To fix the error, you need to clear the carriage return characters using the DOS to Unix command line tool as a text file format converter.


2 Answers

It's your line endings. Transferring it from Windows has left the CR/LF line endings on.

When I create a script then manually add the CR characters, I get exactly the same error:

qq.sh: line 3: syntax error near unexpected token `elif' 'q.sh: line 3: `elif [ 1 == 1 ] ; then 

You can fix it by removing the CR character from CR/LF line endings.

cat script.sh | sed 's/\r//' >newscript.sh 
like image 77
paxdiablo Avatar answered Oct 23 '22 23:10

paxdiablo


Two ways to resolve this

1) Using Sed:-

Syntax

sed -i 's/\r//' filename.txt 

2) Using dos2unix command

Syntax

dos2unix fileName.txt fileName.txt 
like image 21
Sireesh Yarlagadda Avatar answered Oct 24 '22 00:10

Sireesh Yarlagadda