意外令牌'then'附近的语法错误 [英] Syntax error near unexpected token 'then'

查看:160
本文介绍了意外令牌'then'附近的语法错误的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我键入的代码与 Linux命令行相同:完整的简介,第369页 但提示错误:

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`

代码类似于:

#!/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

我想了解是什么导致了错误?如何修改代码?我的系统是Ubuntu.

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

推荐答案

if[之间必须有一个空格,如下所示:

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

这些是等效的:

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

这些也等效:

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

而且,像这样的elif,脚本的中间部分会更好:

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

(我也将引号放在了echo中,因为在此示例中引号是不必要的)

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

这篇关于意外令牌'then'附近的语法错误的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆