简体   繁体   中英

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.

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)

The solution is pretty simple. Just give space between if and the opening square braces like given below.

if [ -f "$File" ]; then <code> fi

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM