2013-11-27 36 views
22

我鍵入的代碼一樣The Linux Command Line: A Complete Introduction,369頁 但提示錯誤:語法錯誤「然後」

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。

回答

48

必須有if[之間的空間,這樣的:

#!/bin/bash 
#test file exists 

FILE="1" 
if [ -e "$FILE" ]; then 
    if [ -f "$FILE" ]; then 
    echo :"$FILE is a regular file" 
    fi 
... 

這些(以及它們的組合)都將是不正確太:

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

這些,另一方面都可以:

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這樣的:

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

(我也放棄了echo的報價,因爲在這個例子中它們是不必要的)

+0

明白了,謝謝,[和-e,E「和]之間都需要空間? –

+0

你需要一個空間的原因是因爲[實際上是一個命令。輸入'which [你會看到它在/ bin /中。你可以寫任何'如果[...];然後命令爲'如果測試...'。 – Coroos