2013-01-25 197 views
0

我試圖在shell中創建一個搜索程序作爲練習,但是當我嘗試用if語句處理空行時,我收到一條消息,說shell遇到意外的操作符。殼如果語句不按預期工作

#!/bin/sh 

file=$1 
token=$2 

while read line 
do 
    if [ ! -z $line ] 
    then 
     set $line 
     if [ $1 = $token ] 
     then 
     echo $line 
     fi 
    fi 
done < $file 

當我運行該程序使用match_token animals_blanks dog我得到

./match_token: 8: [: cat: unexpected operator 
./match_token: 8: [: dog: unexpected operator 
./match_token: 8: [: dog: unexpected operator 
./match_token: 8: [: cow: unexpected operator 
./match_token: 8: [: lion: unexpected operator 
./match_token: 8: [: bear: unexpected operator 
./match_token: 8: [: wolf: unexpected operator 

的animals_blanks文件包含:

cat meow kitten 

dog ruff pup 
dog bark 

cow moo calf 

lion roar cub 

bear roar cub 
wolf howl pup 

回答

2

引用變量:

if [ ! -z "$line" ] 

,但通常情況下,一個會wr ITE:

if [ -n "$line" ] 

當你離開變量加引號,則[命令看到類似:[ -n cat dog ],這是一個錯誤,因爲它預計-n後只有一個參數。通過引用該變量,表達式變爲[ -n "cat dog" ],它只有一個參數,如[所預期的那樣。請注意,確實沒有理由執行該測試,或者使用set;閱讀可以分割線,你當它讀取:

while read animal sound offspring; do 
    test "$animal" = "$token" && echo $animal $sound $offspring 
done < $file