0

I get error [: -lt: unary operator expected after run below script, anyone can share ideas?

temp=0
while [ $temp -lt 25 ]
do
    sleep 1
        echo "running.."

   if [ $temp -eq 5 ]
   then
         top -bc -d 5 -n 1|sed -n '7,8p'|awk '{print $1,$9}'>>out.txt
         temp=`expr $temp +1`
         break
   elif [ $temp -eq 20 ]
   then
         top -bc -d 5 -n 1|sed -n '7,8p'|awk '{print $1,$9}'>>out.txt
         temp=`expr $temp +1`
   else
    temp=`expr $temp +1`
   fi
done
Jeff Schaller
  • 67,283
  • 35
  • 116
  • 255
Shi Jie Tio
  • 177
  • 3
  • 7

1 Answers1

9

Try changing all the +1s after the exprs to + 1.

Without the space expr will return an error and $temp will be empty. If $temp is empty, then the -lt will be comparing a blank space to a number, which is why the error appears. Here's a one liner that reproduces the problem:

t=0;t=`expr $t +1`;[ $t -lt 25 ]

Output (to STDERR):

expr: syntax error
bash: [: -lt: unary operator expected

Better yet, change all code that uses the external util expr to use the shell's own internal arithmetic expansion. So code like this:

temp=`expr $temp +1`

...should be changed to:

temp=$(($temp + 1))

Or, in bash, that whole line can be substituted with just:

((temp++))
agc
  • 7,223