如果语句不按预期工作,则Shell [英] Shell if statements not working as intended

查看:158
本文介绍了如果语句不按预期工作,则Shell的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我试图在shell中创建一个搜索程序作为练习,但是当我尝试使用if语句处理空行时,我收到一条消息,说shell遇到了意外的操作符。

I am attempting to create a search program in shell as an exercise, but when I try to handle empty lines with an if-statement I get a message saying that the shell encountered an unexpected operator.

    #!/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文件包含:

The animals_blanks files contains:

cat meow kitten

dog ruff pup
dog bark

cow moo calf

lion roar cub

bear roar cub
wolf howl pup


推荐答案

引用变量:

 if [ ! -z "$line" ]

但通常会有人写:

 if [ -n "$line" ]

当您保持变量不加引号时, [命令会看到如下内容: [-n cat dog] ,这是一个错误,因为它只需要在 -n 之后只有一个参数。通过引用变量,表达式变为 [-ncat dog] ,它只有一个参数,正如 [。请注意,确实没有理由进行该测试,或使用 set ;当读取时,读取可以为您分割线:

When you leave the variable unquoted, the [ command sees something like: [ -n cat dog ], which is an error because it expects only one argument after -n. By quoting the variable, the expression becomes [ -n "cat dog" ] which has only one argument, as expected by [. Note that there's really no reason to do that test, or to use set; read can split the line for you when it reads:

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

这篇关于如果语句不按预期工作,则Shell的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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