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

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

   if [ $temp -eq 5 ]
         top -bc -d 5 -n 1|sed -n '7,8p'|awk '{print $1,$9}'>>out.txt
         temp=`expr $temp +1`
   elif [ $temp -eq 20 ]
         top -bc -d 5 -n 1|sed -n '7,8p'|awk '{print $1,$9}'>>out.txt
         temp=`expr $temp +1`
    temp=`expr $temp +1`
  • 1
    Do you also get errors from expr? – Michael Homer Jan 14 at 1:52
  • no error shown on expr – Shi Jie Tio Jan 14 at 1:55
  • 2
    Use More Quotes™ – l0b0 Jan 14 at 2:12
  • 1
    Next time please tell us ALL the error messages you get. Not just the last one of a set. You would also have got expr: syntax error. – roaima Jan 14 at 8:47

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:


Not the answer you're looking for? Browse other questions tagged or ask your own question.