如果语句不按预期工作,则Shell

时间:2013-01-25 00:31:56

标签: shell unix if-statement

我试图在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

1 个答案:

答案 0 :(得分:2)

引用变量:

 if [ ! -z "$line" ]

但通常,人们会写:

 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
相关问题