Question

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
Was it helpful?

Solution

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
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top