Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Syntax error near unexpected token 'then'

Tags:

linux

shell

unix

I typed the code the same as The Linux Command Line: A Complete Introduction, page 369 but prompt the error:

line 7 `if[ -e "$FILE" ]; then` 

the code is like:

#!/bin/bash #test file exists  FILE="1" if[ -e "$FILE" ]; then   if[ -f "$FILE" ]; then      echo :"$FILE is a regular file"   fi   if[ -d "$FILE" ]; then      echo "$FILE is a directory"   fi else     echo "$FILE does not exit"    exit 1 fi    exit 

I want to figure out what introduced the error. How can I modify the code? My system is Ubuntu.

like image 215
王奕然 Avatar asked Nov 27 '13 06:11

王奕然


People also ask

What Is syntax error near unexpected token `('?

The error message syntax error near unexpected token `(' occurs in a Unix-type environment, Cygwin, and in the command-line interface in Windows. This error will most probably be triggered when you try to run a shell script which was edited or created in older DOS/Windows or Mac systems.

What does syntax error unexpected?

A parse error: syntax error, unexpected appears when the PHP interpreter detects a missing element. Most of the time, it is caused by a missing curly bracket “}”. To solve this, it will require you to scan the entire file to find the source of the error.

What is unexpected token error in Python?

Unexpected TokenThis is simply down to a syntax error (your fault, I'm afraid). Perhaps you forgot the ':' after a conditional branch or there is an unclosed parenthesis left somewhere in your code? Python scripts are broken down into 'tokens' which helps the program navigate the logic of your code.


1 Answers

There must be a space between if and [, like this:

#!/bin/bash #test file exists  FILE="1" if [ -e "$FILE" ]; then   if [ -f "$FILE" ]; then      echo :"$FILE is a regular file"   fi ... 

These (and their combinations) would all be incorrect too:

if [-e "$FILE" ]; then if [ -e"$FILE" ]; then if [ -e "$FILE"]; then 

These on the other hand are all ok:

if [ -e "$FILE" ];then  # no spaces around ; if     [    -e   "$FILE"    ]   ;   then  # 1 or more spaces are ok 

Btw these are equivalent:

if [ -e "$FILE" ]; then if test -e "$FILE"; then 

These are also equivalent:

if [ -e "$FILE" ]; then echo exists; fi [ -e "$FILE" ] && echo exists test -e "$FILE" && echo exists 

And, the middle part of your script would have been better with an elif like this:

if [ -f "$FILE" ]; then     echo $FILE is a regular file elif [ -d "$FILE" ]; then     echo $FILE is a directory fi 

(I also dropped the quotes in the echo, as in this example they are unnecessary)

like image 68
janos Avatar answered Sep 20 '22 03:09

janos