4

I am trying to debug someone else's script:

The code line is:

y=$((${oldvalue[$x]}-${newvalue[$x]}))

y gets calculated fine as long as both sides are positive numbers. However, I have a production situation where they are both negative and the error I get is:

DEBUG Old value = -4144290000
DEBUG New value = -4009685000
script.sh: line 123: -4144290000--4009685000: assignment requires lvalue

I never would use ksh myself for even the simplest of calculations but I am in a position of production support and have to deal with a big ball of mud, I would use at least Perl/Python. Can anybody tell why this problem is happening and how to fix it?

5

If you're using the $xxx syntax, then the variable is expanded, and then the result is evaluated as an arithmetic expression.

So,

y=$((${oldvalue[$x]}-${newvalue[$x]}))

Becomes

y=$((-4144290000--4009685000))

and ksh complains about that unexpected -- operator.

You can get around it by adding spaces as you found out, in which case it becomes:

y=$((-4144290000 - -4009685000))

But, you could also write it:

y=$((oldvalue[$x]-newvalue[$x])))

In that case, the content of the variable is expanded as part of the arithmetic evaluation and in that case as one numerical value.

The different becomes even more important in cases like:

a=1+1 b=2
echo "$((a*b)) vs $(($a*$b))"

Which gives 4 vs 3, and points to a third and more robust than the first way to work around the problem:

y=$(((${oldvalue[$x]}) - (${newvalue[$x]})))
0
0

It needed spaces on both sides of the minus:

y=$((${oldvalue[$x]} - ${newvalue[$x]}))
1
  • 2
    Just to explain further, this is because -- was interpreted as a decrement operator.
    – Random832
    Dec 27 '12 at 20:40

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

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