Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
295 views
in Technique[技术] by (71.8m points)

unix - Shell if statements not working as intended

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

When I run the program using match_token animals_blanks dog I get

./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

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
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

Quote the variable:

 if [ ! -z "$line" ]

but normally, one would write:

 if [ -n "$line" ]

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

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

2.1m questions

2.1m answers

60 comments

56.8k users

...