Tuesday, January 26, 2010

bash numeric comparison

Ah, just ran into the dreaded bash comparison error again.  And I know better.  But in my defense, I'm cleaning up some scripts circa 1996.

OK, there is no good defense.  This is a miserable excuse for a loop.

 loops=1

  until test -z "`ps -e|grep icexec`"
  do
{some stuff you want to do here}
    if [[ $loops > 10 ]]  
        then
    exit 0
    fi

   let loops='loops + 1'
  done

This is just bad in so many ways, it's hard to decide where to start.  Let's go with the math functions first.

if [[ loops > 10 ]] just doesn't work.  It does an ASCII comparison, so the second time through it exits out, since '2' is larger than '1'.  Change it to if [[ loops -gt 10 ]].  Or, better still, use two parentheses, and make it if ((loops > 10)).  Much cleaner.

Incrementing the loop.  This works, but I hate the 'let' command.  It's so damn picky about whitespace.  Change it to parentheses again, ((loops = loops+1)).  Or, again better, ((loops++)).

So your code is now

  until test -z "`ps -e|grep icexec`"
  do
 {some stuff you want to do here}

 if ((loops > 10))
        then
  exit 0
  fi
  ((loops++))
done

Better.  But why bother with the inner 'if...then'?

  until test -z "`ps -e|grep icexec`"||((loops > 10))
  do
 {some stuff you want to do here}
    ((loops++))
done

No comments:

Post a Comment