Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
733 views
in Technique[技术] by (71.8m points)

linux - Syntax error near unexpected token 'then'

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.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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)


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...